Parse JSON Array - java

My JSON is something like this:
[{
"myviews":[{
"2011-05-12_2011-05-14":{
"name":"thiswk",
"data":[[12,
2403
],
[13,
2082
],
[14,
5823
]
]
}
},
{
"2011-06-05_2011-06-7":{
"name":"lastwk",
"data":[[5,
1279
],
[6,
6685
],
[7,
2163
]
]
}
}
]
}
]
JSONObject jo = new JSONObject(jsonString);
JSONArray ja;
jo = jo.getJSONObject("2011-05-12_2011-05-14");
ja = jo.getJSONArray("data");
int resultCount = ja.length();
for (int i = 0; i < resultCount; i++)
{
JSONObject resultObject = ja.getJSONObject(i);
resultObject.getJSONArray("12");
System.out.println("--");
}
I am unable to read the values under the "data" array. Get this error
Exception in thread "main"
org.json.JSONException: A JSONObject
text must begin with '{' at character
1

You're trying to create a JSONObject based on a string that doesn't represent an object, but an array containing one object.
To get the contained object, try
JSONArray inputArray = new JSONArray(jsonString);
JSONObject jo = inputArray.getJSONObject(0);
I think some of your later work is wrong as well, but perhaps this will get you started.

data appears to be an array of arrays. Perhaps you need to call ja.getJSONArray(i)?

Related

Why does my Spring project return A JSONArray text must start with '[' at 1?

I'm new to Spring Boot and json so forgive me if a silly question. I'm trying to read in my json file, convert it to a JSONObject, then
convert this to a JSONArray. I've commented out the two lines which do
this as I tried going from reading the file to the Array instead. My
JSON file starts with a [ so I'm unsure why I get this error.
Exception in thread "main" org.json.JSONException: A JSONArray text
must start with '[' at 1 [character 2 line 1]
InputStream inputStream = TypeReference.class.getResourceAsStream("/json/req.json");
List<PIECase> allCases = new ArrayList<PIECase>();
InputStream rawJson = inputStream;
//JSONObject jsonObject = new JSONObject(rawJson);
//JSONArray jsonArray = jsonObject.getJSONArray("PIECases");
JSONArray jsonArray = new JSONArray(rawJson.toString());
for(int i =0; i < jsonArray.length(); i++) {
//the JSON data we get back from array as a json object
JSONObject jsonPIECases = jsonArray.getJSONObject(i);
// more code
}
req.json
[
{
"PIECases": {
"PIECases": [
{
"Case_ID": "1",
"SortCode": "123456",
"AccountNumber": "12345678",
"Amount": "50",
"DateOfPayment": "2019-07-29"
},
{
"Case_ID": "2",
"SortCode": "123456",
"AccountNumber": "12345678",
"Amount": "50",
"DateOfPayment": "2019-07-29"
}
]
}
}
]
rawJson.toString() does not return the json content but just the result of default Object#toString() method of the InputStream, use;
JsonReader jsonReader = Json.createReader(inputStream);
JsonArray array = jsonReader.readArray();
jsonReader.close();
from JsonArray

How to access elements in java subarray without key but with index

I have an JSON that looks like this:
{ "Message": "None", "PDFS": [
[
"test.pdf",
"localhost/",
"777"
],
[
"retest.pdf",
"localhost\",
"666"
] ], "Success": true }
I'm trying to access the individual strings within the arrays but I'm having difficulty doing it as getString is requiring me to use a key and not indexes.
I've tried this to access the first string in each sub-array:
JSONArray pdfArray = resultJson.getJSONArray("PDFS");
for (int i = 0; i < pdfArray.length(); i++) {
JSONObject pdfObject = pdfArray.getJSONObject(i);
String fileName = pdfObject.getString(0);
}
Read the array as an array:
JSONArray array = pdfArray.getJSONArray(i);
String fileName = array.getString(0);

Search for a particular item in place types in google map json data

I tried to find particular item types in JSON data.
Like
"types": [
"restaurant",
"food",
"lodging",
"point_of_interest",
"establishment"
],
"types": [
"meal_delivery",
"restaurant",
"food",
"point_of_interest",
"establishment"
],
Some times restaurant is coming in 0th position sometimes in 1st position.
How to find weather types contains "restaurant" or not
You need to iterate through the JSON Array of "types" and check whether it contains "restaurant" -
JSONObject obj = new JSONObject(jsonString);
JSONArray arr = obj.getJSONArray("types");
for (int i = 0; i < arr.length(); i++)
if("restaurant".equals(arr.get(i).toString())){
}
The response you are getting is jsonobject get the json array and compare with the required string
JSONObject jObj = new JSONObject(response);
JSONArray jAry= jObj.getJSONArray("types");
String str="restaurant";
for (int i = 0; i < arr.length(); i++){
if(str.equalsIgnoreCase(jAry.get(i).toString())){
//do whatever you want
}
}
it will work for you.
JSONObject jObj = new JSONObject(response);
JSONArray jsonArray= jObj.getJSONArray("types");
boolean s = false;
if (s==jsonArray.toString().contains("restaurant"))
{
}

org.json.JSONException: A JSONObject text must begin with '{' at 1 [character 2 line 1]

Iam parsing a json using org.json in java . My json list like:
[ {
"id": "f187b01b145c4171b66d4a2ecabb8f44"
},
{
"id": "a5e66b7462e24924a03e89f0619a2398"
},
{
"id": "2fb3627360db4ab78a0b3f27527b1983"
} ]
I fetch data from the java code :
JSONObject json = new JSONObject(response.getEntity(String.class));
Jobs[] obj = new Gson().fromJson(json.toString(), Jobs[].class);
System.out.println(obj.toString());
But it gives an exception :
Exception in thread "main" org.json.JSONException: A JSONObject text must begin with '{' at 1 [character 2 line 1]
at org.json.JSONTokener.syntaxError(JSONTokener.java:433)
at org.json.JSONObject.<init>(JSONObject.java:197)
at org.json.JSONObject.<init>(JSONObject.java:324)
at br.usp.icmc.teste.ConnectionRestClient.getSaucelabsGetJobs(ConnectionRestClient.java:80)
at br.usp.icmc.teste.TestePrincipal.main(TestePrincipal.java:9)
why it did not recognized as JSONArray ? Where am I wrong ?
U can try with below code. There are many ways to do it, below is one of the way
JSONArray jsonArray = new JSONArray(response.getEntity(String.class));
for(int i =0; i< jsonArray.length(); i++){
if(jsonArray.get(i) instanceof JSONObject){
JSONObject jsnObj = (JSONObject)jsonArray.get(i);
String finalValue = (String)jsnObj.get("id");
}
}

A JSONObject text must begin with '{' error

I have this JSON coming from one of our REST service:
[
"{\"category_name\":[\"Industry Components\"],\"categoryId\":[1]}",
"{\"category_name\":[\"Business Components\"],\"categoryId\":[2]}",
"{\"category_name\":[\"Utilities\"],\"categoryId\":[3]}",
"{\"category_name\":[\"Tools\"],\"categoryId\":[4]}
]
I am using java-json.jar to parse this JSON, this is the simple snippet where I am trying to pass above JSON string:
JSONObject jsonObject = new JSONObject(jsonStr);
But I am getting below exception:
org.json.JSONException: A JSONObject text must begin with '{' at 1 [character 2 line 1]
First I assumed it's because of [ and ] characters in JSON and I tried to replace as below:
String replacedStr = jsonStr.replaceAll("\\[", "").replaceAll("\\]", "")
But even then I am getting same exception. Can anyone please guide me to know what I am doing wrong?
I suppose that you should use not JSONObject, but JSONArray
JSON Object follows the following Structure:
{
"array": [
{
color: "red",
value: "#f00"
},
{
color: "green",
value: "#0f0"
}
]
}
JSON Array follows the following Structure:
[
{ "firstName":"John" , "lastName":"Doe" },
{ "firstName":"Anna" , "lastName":"Smith" },
{ "firstName":"Peter" , "lastName": "Jones" }
]
instead
JSONObject jsonObject = new JSONObject(jsonStr);
use
JSONArray jsonArray = new JSONArray(jsonStr);
and may be read about Gson is a nice library for parsing and work with json
If you get JSONObject text must begin with '{' exception.
Then first off all check what did u pass to the JSONObject constructor.
You should pass the right json.txt file.So make sure what are u passing to jsonobject.
String request = FileUtils.readFileToString(new File("/home/achaure/Downloads/Amol/KountRestTest/Documents/request.txt"));
JSONObject jsonObject = new JSONObject(request);

Categories