Incorrect JSONException - java

I'm trying to use JSON objects from the Guardian API.
This is the result from my call:
https://pastebin.com/wqggLEeZ
This is my code
JSONObject root = new JSONObject(jsonData);
JSONArray resultArray = root.getJSONObject("response").getJSONArray("results");
for(int i=0;i<resultArray.length();i++) {
JSONObject resultElement = resultArray.getJSONObject(i);
JSONObject blocksElement = resultElement.getJSONObject("blocks");
JSONObject mainElement = blocksElement.getJSONObject("main");
JSONArray elementsArray = mainElement.getJSONArray("elements");
JSONObject elementsElement = elementsArray.getJSONObject(0);
JSONArray assetsArray = elementsElement.getJSONArray("assets");
JSONObject assetsElement = assetsArray.getJSONObject(0);
String imageUrl = assetsElement.getString("file");
String articleTitle = resultElement.getString("webTitle");
news.add(new NewsList(articleTitle, imageUrl));
}
The code works fine except that it stops at 3 elements (i=2)
I tried replacing the imageUrl with "test" string in
news.add(new NewsList(articleTitle, imageUrl));
but it still stops at 3 elements.
But when I comment out the part where it finds the imageUrl the whole code works and gives me 10 results like it should do:
JSONObject root = new JSONObject(jsonData);
JSONArray resultArray = root.getJSONObject("response").getJSONArray("results");
for(int i=0;i<resultArray.length();i++){
JSONObject resultElement = resultArray.getJSONObject(i);
/*
JSONObject blocksElement = resultElement.getJSONObject("blocks");
JSONObject mainElement = blocksElement.getJSONObject("main");
JSONArray elementsArray = mainElement.getJSONArray("elements");
JSONObject elementsElement = elementsArray.getJSONObject(0);
JSONArray assetsArray = elementsElement.getJSONArray("assets");
JSONObject assetsElement = assetsArray.getJSONObject(0);
String imageUrl = assetsElement.getString("file");
*/
String articleTitle = resultElement.getString("webTitle");
news.add(new NewsList(articleTitle, "test"));
}
I've looked around in Android monitor and it seems like it has a problem that says
org.json.JSONException: No value for main
But that is not correct as the URL for the first 3 result is found without any problem, the problem only occurs after 3 iterations of the loop and I can't find any reason for why this is happening.

Use everywhere "opt" instead of "get', e.g.:
JSONObject assetsElement = assetsArray.optJSONObject(0);
String imageUrl = assetsElement.optString("file");

this is happening because of there is no field "main" in the response at some position in the line
JSONObject mainElement = blocksElement.getJSONObject("main");
so if at any of the position any of the fields are missing from the response, then after that position the code will not compile in JSON parsing.
sorry for bad english .

Related

Getting attribute values from JSON String in Java

Hello I am building a Spring Boot app with Thymeleaf and I am receiving from an API a JSON that I have to put in the HTML page. This is the JSON:
{"mesaje":[{"data_creare":"202205191249","cif":"1111111111118","id_solicitare":"205804","detalii":"Erori de validare identificate la factura primita cu id_incarcare=205804","tip":"ERORI FACTURA","id":"9279339"}
This is what I have tried:
String raspuns = service.getListaMesaje(zile, select);
System.out.println("------------------------"+raspuns);
JsonParser parser = new JsonParser();
JsonObject obj = parser.parse(raspuns).getAsJsonObject();
//String eroare = obj.get("eroare").getAsString();
String mesaje = obj.get("mesaje").getAsString();
JSONObject responseObject = new JSONObject(raspuns);
JSONArray jsonArray = (JSONArray) responseObject.get("mesaje");
JSONObject jsonObject = (JSONObject) jsonArray.get(0);
String dataCreare = jsonObject.getString("data_creare");
model.addAttribute("data_creare", dataCreare);
In the console the JSON prints but I get this error also in the console:
java.lang.IllegalStateException: null
Can someone show me an example how to extract the values from mesaje parent in the JSON ?
Thank you
I suggest you to use gson library for that.
Then, after you added gson dependency in pom.xml, you can extract values from your JSON string with this few lines of code :
String raspuns = "{\"mesaje\":[{\"data_creare\":\"202205191249\",\"cif\":\"1111111111118\",\"id_solicitare\":\"205804\",\"detalii\":\"Erori de validare identificate la factura primita cu id_incarcare=205804\",\"tip\":\"ERORI FACTURA\",\"id\":\"9279339\"}]}";
JsonObject jsonObject = new JsonParser().parse(raspuns).getAsJsonObject();
JsonArray arr = jsonObject.getAsJsonArray("mesaje");
for (int i = 0; i < arr.size(); i++) {
String data_creare = arr.get(i).getAsJsonObject().get("data_creare").getAsString();
String cif = arr.get(i).getAsJsonObject().get("cif").getAsString();
String id_solicitare = arr.get(i).getAsJsonObject().get("id_solicitare").getAsString();
String detalii = arr.get(i).getAsJsonObject().get("detalii").getAsString();
String tip = arr.get(i).getAsJsonObject().get("tip").getAsString();
String id = arr.get(i).getAsJsonObject().get("id").getAsString();
System.out.println(data_creare);
System.out.println(cif);
System.out.println(tip);
System.out.println(id_solicitare);
System.out.println(detalii);
System.out.println(id);
}

Android Java JsonObject put only last value

im been working apps with booking system, and i have problem with generate json and send it to server. the server catch this json
"buy":{
"583":[
{
"title":"Mr",
"nama_depan":"Mulia Rifai Aroyan",
"nama_belakang":"",
"tanggal_lahir":"0000-0-0",
"nationality":"Indonesia",
"identitas":"identitas",
"kelas_id":"254",
"kelas":"B",
"harga":"60000",
"seat":""
}
],
"584":[
{
"title":"Mr",
"nama_depan":"Mulia Rifai Aroyan",
"nama_belakang":"",
"tanggal_lahir":"0000-0-0",
"nationality":"Indonesia",
"identitas":"identitas",
"kelas_id":"254",
"kelas":"B",
"harga":"60000",
"seat":""
}
]
}
and i create generated json like this :
final JSONObject buy_child = new JSONObject();
final JSONArray buy = new JSONArray();
final JSONObject detail = new JSONObject();
for (int i=0;i<list_id_content.size();i++)
{
detail.put("title",gelar);
detail.put("nama_depan",nama_depan);
detail.put("nama_belakang",nama_belakang);
detail.put("tanggal_lahir",tanggal_lahir);
detail.put("nationality",nationality);
detail.put("identitas",identitas);
detail.put("kelas_id",id_event);
detail.put("kelas",kelas);
detail.put("harga",total_harga_pertiket);
detail.put("seat","");
buy.put(detail);
buy_child.put(id_event_content2,buy);
}
but its seems only generate json with same value (the last value)
how can i generate json like that and get all the value inside the loop?
thanks
edited : if i put JSONObject detail = new JSONObject(); inside the loop, it will give me this
Put the JSONObject detail = new JSONObject(); inside the for loop at the beginning.
Then put buy.put(detail); at the end of the loop (but inside).
You're only getting the last one right now because the buy.put is outside the for loop.
try with this
final JSONObject buy_child = new JSONObject();
final JSONArray buy;
for (int i=0;i<list_id_content.size();i++)
{
buy= new JSONArray();
final JSONObject detail = new JSONObject();
detail.put("title",gelar);
detail.put("nama_depan",nama_depan);
detail.put("nama_belakang",nama_belakang);
detail.put("tanggal_lahir",tanggal_lahir);
detail.put("nationality",nationality);
detail.put("identitas",identitas);
detail.put("kelas_id",id_event);
detail.put("kelas",kelas);
detail.put("harga",total_harga_pertiket);
detail.put("seat","");
buy.put(detail);
}
buy_child.put(id_event_content2,buy);

Not Finding JSON ARRAY value within the JSON Object in JAVA - ANDROID

I am obtaining a JSON response from an API which contains color information.
This is the response:
enter image description here
I want to be able to access the html_code value from the background_colors array within the info JSON object.
Firstly, have tried doing this simply with this code:
result = stack.getBody().getObject().toString(2);
JSONObject parentObject = new JSONObject(_result);
JSONArray jr = parentObject.getJSONArray("results");
JSONObject jb1 = jr.getJSONObject(0);
System.out.print(jb1);
This prints me out the info Object as expected.
However, if I try and access the JSON Array "background_colors" using this,
JSONObject parentObject = new JSONObject(_result);
JSONArray jr = parentObject.getJSONArray("results");
JSONObject jb1 = jr.getJSONObject(0);
System.out.print(jb1);
JSONArray jsonArray =
jb1.getJSONArray("background_colors");
System.out.print(jsonArray);
I get this error: No value for "background_colors".
I know this error means that the background_colors array does not exist in the JSONObject but I have no idea how and why this would be the case?
Any help would be much appreciated.
background_colors is a property of the info object not the root object from the array.
Try this:
JSONObject parentObject = new JSONObject(_result);
JSONArray jr = parentObject.getJSONArray("results");
JSONObject jb1 = jr.getJSONObject(0).getJSONObject("info");
JSONArray jsonArray = jb1.getJSONArray("background_colors");
System.out.print(jsonArray);
JSONObject jb1 = jr.getJSONObject(0).getJSONObject("info");
JSONArray jsonArray = jb1.getJSONArray("background_colors");

Getting Json object inside a Json object in Java

So I have some code that is able to send this out:
{"id":1,
"method":"addWaypoint",
"jsonrpc":"2.0",
"params":[
{
"lon":2,
"name":"name",
"lat":1,
"ele":3
}
]
}
The server receives this JSON object as a string named "clientstring":
JSONObject obj = new JSONObject(clientstring); //Make string a JSONObject
String method = obj.getString("method"); //Pulls out the corresponding method
Now, I want to be able to get the "params" value of {"lon":2,"name":"name","lat":1,"ele":3} just like how I got the "method".
however both of these have given me exceptions:
String params = obj.getString("params");
and
JSONObject params = obj.getJSONObject("params");
I'm really at a loss how I can store and use {"lon":2,"name":"name","lat":1,"ele":3} without getting an exception, it's legal JSON yet it can't be stored as an JSONObject? I dont understand.
Any help is VERY appreciated, thanks!
params in your case is not a JSONObject, but it is a JSONArray.
So all you need to do is first fetch the JSONArray and then fetch the first element of that array as the JSONObject.
JSONObject obj = new JSONObject(clientstring);
JSONArray params = obj.getJsonArray("params");
JSONObject param1 = params.getJsonObject(0);
How try like that
JSONObject obj = new JSONObject(clientstring);
JSONArray paramsArr = obj.getJSONArray("params");
JSONObject param1 = paramsArr.getJSONObject(0);
//now get required values by key
System.out.println(param1.getInt("lon"));
System.out.println(param1.getString("name"));
System.out.println(param1.getInt("lat"));
System.out.println(param1.getInt("ele"));
Here "params" is not an object but an array. So you have to parse using:
JSONArray jsondata = obj.getJSONArray("params");
for (int j = 0; j < jsondata.length(); j++) {
JSONObject obj1 = jsondata.getJSONObject(j);
String longitude = obj1.getString("lon");
String name = obj1.getString("name");
String latitude = obj1.getString("lat");
String element = obj1.getString("ele");
}

simpleJson parsing in Java

I'm very new to parsing JSON. I have looked all over and cannot seem to grasp the idea to my particular problem. I'm having a hard time understanding how to get a JSON object from a JSON array. My example is below
[{"styleId":94,
"status":"verified",
"abv":"4.2",
"name":"Bud Light"}]
Here is my current code
JSONParser parser = new JSONParser();
Object obj = parser.parse(inputLine);
JSONObject jsonObject = (JSONObject) obj;
Long currPage = (Long)jsonObject.get("currentPage");
System.out.println(currPage);
JSONArray jArray = (JSONArray)jsonObject.get("data");
System.out.println(jArray);
inputLine is my orignal JSON. I have pulled a JSONArray out of the original JSONObject that has the "data" tag. Now this is where I'm stuck and given the JSONArray at the top. Not sure how to iterate through the Array to grab JUST the "name" tag.
Thanks for the help in advanced!
To iterate in a JSONArray you need to go through each element in a loop.
int resultSize = jArray.length();
JSONObject result;
for (int i = 0; i < resultSize; i++) {
result = resultsArray.getJSONObject(i);
String name = result.getString("name");
// do whatever you want to do now...
}
just use Gson . it works well out of the box with any object type you supply.
This is an example from the user's guide:
int[] ints2 = gson.fromJson("[1,2,3,4,5]", int[].class);

Categories

Resources