Json reponse with repeated json objects without parent json arry - java

Above is the json response I am receiving from a url. There are repeated json objects in the response at the same level without a parent json array, I believe that these objects should be within a josn array so one can loop through the objects to access their information.
Is it really an error of missing json array? if not then how can be looped through and receive information in such scenario. Thanks for your time and help.

How can be looped through and receive information in such scenario ?
You should use ITERATOR for this case .
FYI
Iterator is a way to traverse the data over the collection objects.
JSONObject jOBJECT = new JSONObject(success);
Iterator iteratorObj = jOBJECT.keys();
while (iteratorObj.hasNext())
{
String getJsonObj = (String)iteratorObj.next();
System.out.println("Key: " + Key + "------>" + getJsonObj); // 78,40,121,132
}

Here is the detailed solution for such pattern of objects in the service response.
https://stackoverflow.com/a/12870643/1925394

this code maybe can help you:
try {
String data="";//this is you json
JSONObject jsonObject=new JSONObject(data);
JSONArray messages = jsonObject.getJSONArray("message");//get a array
//loop the arrat to output
for (int i = 0; i < messages.length(); i++) {
JSONObject msg=messages.getJSONObject(i);
String id= msg.getString("id");
String username= msg.getString("username");
System.out.println("id:"+id+",username:"+username);
}
} catch (JSONException e) {
e.printStackTrace();
}
but,I advise you don't use this in your project, you can consider Gson ,use this you can transfer json to java model,and then it's easy to use.

Related

How to access the JSON element?

#Override
protected void onPostExecute(String response) {
String firstName = null;
String lastName = null;
try {
JSONObject jsonResponse = new JSONObject(response);
JSONArray jsonArray = jsonResponse.getJSONArray("");
JSONObject userInfo = jsonArray.getJSONObject(0);
firstName = userInfo.getString("id");
lastName = userInfo.getString("id");
}
catch (JSONException e){
e.printStackTrace();
}
I have this JSON file https://api.myjson.com/bins/1a5t7w
How i can acces to thats values, i used this code but it doesn`t work?
It returns #null#
You are getting a JSON array in the response.
To parse this array you need to pass the response to JSONArray object like below
try {
JSONArray rspArr = new JSONArray(response);
for(int i= 0; i< rspArr.length(); i++){
JSONObject jsonObject = (JSONObject) rspArr.get(i);
//Your logic
}
}catch (Exception e ){
//log exception
}
// since you know is an array, create a JSONArray based on your response String
JSONArray array = JSONArray(response)
// obtain the first element of your array as a JSONObject
JSONObject jsonObject = array.getJSONObject(0)
// once you get the jsonObject you can start getting the values you need
String id = jsonObject.getString("id")
Hope it helps!
Answer by Arunangshu seems correct, you need to extract the JSONArray first because the API is returning JSONArray(array of JSON objects) and not one big JSON object.
One can use http://jsonviewer.stack.hu/ for viewing JSON. It gives better understanding of the JSON structure.
For Java, one can use http://www.jsonschema2pojo.org/ for converting JSON object(not array) to Java Pojo class (select the options carefully).
Following is the first object from json array -
{"id":48191,"title":"Apple Crumble Recipe","image":"https://spoonacular.com/recipeImages/48191-312x231.jpg","imageType":"jpg","usedIngredientCount":1,"missedIngredientCount":2,"missedIngredients":[{"id":4073,"amount":35.0,"unit":"g","unitLong":"grams","unitShort":"g","aisle":"Milk, Eggs, Other Dairy","name":"margarine","original":"35 g margarine or butter","originalString":"35 g margarine or butter","originalName":"margarine or butter","metaInformation":[],"meta":[],"image":"https://spoonacular.com/cdn/ingredients_100x100/butter-sliced.jpg"},{"id":8120,"amount":35.0,"unit":"g","unitLong":"grams","unitShort":"g","aisle":"Cereal","name":"rolled oats","original":"35 g rolled oats","originalString":"35 g rolled oats","originalName":"rolled oats","metaInformation":[],"meta":[],"image":"https://spoonacular.com/cdn/ingredients_100x100/rolled-oats.jpg"}],"usedIngredients":[{"id":9003,"amount":400.0,"unit":"g","unitLong":"grams","unitShort":"g","aisle":"Produce","name":"apples","original":"400 g cooking apples peeled cored and quartered","originalString":"400 g cooking apples peeled cored and quartered","originalName":"cooking apples peeled cored and quartered","metaInformation":["cored","peeled","quartered"],"meta":["cored","peeled","quartered"],"image":"https://spoonacular.com/cdn/ingredients_100x100/apple.jpg"}],"unusedIngredients":[],"likes":965}

Get the count of entries from a json file

I am trying to get json data from a fake api call and need to get the count of the items in it(so that in future I can call the actual restful service). I am not able to get the number of departments in the json. I am expecting the result as 4(int) here.
I am not able to get the string value(json) for the code below:
String json = client.target("file:///C:/Program%20Files%20(x86)/apache-tomcat-8.0.35/webapps/GetProducts.json").request(MediaType.TEXT_PLAIN).get(String.class);
Please find below the entire code:
String json = client.target("file:///C:/Program%20Files%20(x86)/apache-tomcat-8.0.35/webapps/GetProducts.json").request(MediaType.TEXT_PLAIN).get(String.class);
JSONObject jsnobject = new JSONObject(json);
JSONArray jsonArray = jsnobject.getJSONArray("locations");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject explrObject = jsonArray.getJSONObject(i);
}
JSON Sample:
{
"Department":
[
{"SectionId":"1","SectionName":"Childrens Wear"},
{"SectionId":"2","SectionName":"Womens Wear"},
{"SectionId":"3","SectionName":"F&A"},
{"SectionId":"1","SectionName":"Mens Wear"}
]
}
I am new to java as well as api's.
Thanks,
You are either using incorrect key in code or you posted incorrect JSON example. You used locations as the key incode however there is no value against that key in sample JSON. You need to use Department as the key.
JSONArray jsonArray = jsnobject.getJSONArray("Department");

parse json using java (simplejson)

I need to parse json which I get from YQL but I am having trouble as I am not getting the results I need. I am using simple json (https://code.google.com/p/json-simple/wiki/DecodingExamples) and trying to follow the documentation. The problem is the example they show are very limited (I am very new to json). I want to extract everything in the array (Sy, Date, O, H, L, C, and V ). In the documentation they show how to extarct elements from an array if the json object is just as an array, but I have an array + some extra stuff on top:
{"query"
{"count":200,"created":"2014-06-17T00:46:43Z","lang":"en-GB","results"
This is the full json object, how would I extract just the array?
{"query"
{"count":200,"created":"2014-06-17T00:46:43Z","lang":"en-GB","results"
{"array":[{"Sy":"Y","Date":"2010-03-10","O":"16.51","H":"16.94","L":"16.51","C":"16.79","V":"33088600"},
{"Sy":"Y","Date":"2010-03-09","O":"16.41","H":"16.72","L":"16.40","C":"16.53","V":"20755200"},
{"Sy":"Y","Date":"2010-03-08","O":"16.32","H":"16.61","L":"16.30","C":"16.52","V":"30554000"}
]}}}
i use https://code.google.com/p/org-json-java/downloads/list
this is simple
try{
String json = "JSON source";
JSONObject j = new JSONObject(json);
JSONArray arr = j.getJSONObject("query").getJSONObject("results").getJSONArray("array");
for(int i=0; i<arr.length(); i++){
JSONObject obj = arr.getJSONObject(i);
String sy = obj.getString("Sy");
String date = obj.getString("Date");
String o = obj.getString("O");
String h = obj.getString("H");
String l = obj.getString("L");
String c = obj.getString("C");
String v = obj.getString("V");
}
}
catch(JSONException e){
}
You have to extract the array you need piece by piece.
JSONParser parser=new JSONParser();
String s="{YOUR_JSON_STRING}";
JSONArray array=parser.parse(s).get("query") //"query"
.get("result") // "query->result"
.get("array"); // THE array you need
Note that you might need to use try...catch... block to deal with exceptions.
Since you are using java, I highly recommend gson, which is written by google. It can convert json to object directly, which means you don't need to get the array deep inside the json step by step. https://code.google.com/p/google-gson/
Generally speaking, you can use gson to parse json piece by piece with jsonparser or, convert the whole json to a object with gson.

How to access nested objects of a Json File

the string I have into "jsonString" is the content of this link: http://85.18.173.82/cineca/wp5/json/events.json
Now I want the value "Day" of the second "Event".
JSONObject o = new JSONObject(jsonString);
String day = o.getString("XXXXXXXXXX");
System.out.println(day);
What does I have to put as argument of o.getString?
Many thanks
JSONObject obj = new JSONObject(json);
JSONArray array = obj.getJSONArray("Events");
for(int i = 0 ; i < array.length() ; i++){
System.out.println(array.getJSONObject(i).getJSONObject("Event").getString("Day"));
}
In this way, you can access, thanks.
The way you're constructing your JSONObject is wrong. By using this constructor you're not reading the json from that URL, you're actually using that string as a json representation (which it is not).
If you want to first read the json from your URL you'll have to do an HTTP GET request and then construct a JSONObject out of the response.
For more info, take a look at JSONObject docs

java nested JSONArray

I want to know if it is possible to check if some key exists in some jsonArray using java. For example: lets say that I have this json string:
{'abc':'hello','xyz':[{'name':'Moses'}]}
let's assume that this array is stored in jsnArray from Type JSONArray.
I want to check if 'abc' key exists in the jsnArray, if it exists I should get true else I should get false (in the case of 'abc' I should get true).
Thnkas
What you posted is a JSONObject, inside which there is a JSONArray. The only array you have in this example is the array 'xyz', that contains only one element.
A JSONArray example is the following one:
{
'jArray':
[
{'hello':'world'},
{'name':'Moses'},
...
{'thisIs':'theLast'}
]
}
You can test if a JSONArray called jArray, included inside a given JSONObject (a situation similar to the example above) contains the key 'hello' with the following function:
boolean containsKey(JSONObject myJsonObject, String key) {
boolean containsHelloKey = false;
try {
JSONArray arr = myJsonObject.getJSONArray("jArray");
for(int i=0; i<arr.length(); ++i) {
if(arr.getJSONObject(i).get(key) != null) {
containsHelloKey = true;
break;
}
}
} catch (JSONException e) {}
return containsHelloKey;
}
And calling that in this way:
containsKey(myJsonObject, "hello");
Using regular expressions will not work because of the opening and closing brackets.
You could use a JSON library (like google-gson) to transform your JSON Array into a java array and then handle it.
JSON arrays don't have key value pairs, JSON objects do.
If you store it as a json object you can check the keys using this method:
http://www.json.org/javadoc/org/json/JSONObject.html#has(java.lang.String)
If you use JSON Smart Library in Java to parse JSon String -
You can parse JSon Array with following code snippet -
like -
JSONObject resultsJSONObject = (JSONObject) JSONValue.parse(<<Fetched JSon String>>);
JSONArray dataJSon = (JSONArray) resultsJSONObject.get("data");
JSONObject[] updates = dataJSon.toArray(new JSONObject[dataJSon.size()]);
for (JSONObject update : updates) {
String message_id = (String) update.get("message_id");
Integer author_id = (Integer) update.get("author_id");
Integer createdTime = (Integer) update.get("created_time");
//Do your own processing...
//Here you can check null value or not..
}
You can have more information in - https://code.google.com/p/json-smart/
Hope this help you...

Categories

Resources