How to parse this json in android studio? - java

{
"result_count": 251175,
"images": [
{
"id": "649682800",
"display_sizes": [
{
"is_watermarked": false,
"name": "thumb",
"uri": "https://media.gettyimages.com/photos/sergi-roberto-of-barcelona-celebrates-as-he-scores-their-sixth-goal-picture-id649682800?b=1&k=6&m=649682800&s=170x170&h=UjuhQ2k4pOnhCh5a1oLuC4t5rwX8332a-PEqZ8dpUfY="
}
],
"referral_destinations": [
{
"site_name": "gettyimages",
"uri": "https://www.gettyimages.com/detail/news-photo/sergi-roberto-of-barcelona-celebrates-as-he-scores-their-news-photo/649682800"
}
],
"title": "FC Barcelona v Paris Saint-Germain - UEFA Champions League Round of 16: Second Leg"
}

The above JSON Data is missing ] } . So make the data a valid JSON by adding ] } at the end
JSONObject jsonObject = new JSONObject(response);
JSONArray jsonArray = jsonObject.optJSONArray("images");
for(int i=0; i< jsonArray.length(); i++)
{
JSONObject jsonObjec = jsonArray.optJSONObject(i);
jsonObjec.optString("id");
jsonObjec.optString("title");
JSONArray display_sizes = jsonObjec.optJSONArray("display_sizes");
// get the display_sizes Array details
JSONArray referral_destinations = jsonObjec.optJSONArray("referral_destinations");
// get the referral_destinations Array details
}

First it is invalid json.
Try using gson library to parse the json.
Try this link
gson library to parse json

Related

How to extract JSONArray and JSONObject from a JSON in Java

How can I extract JSON Array and JSON Object from JSON.
Below is the input:
{
"messageName": "ReportCard",
"orgId": "Org1",
"comment": true,
"Fields": [{
"objectId": "1234-56789-asdv",
"fieldId": "1245-7852-dhjd"
},
{
"objectId": "1234-56hgjgh789-hjjhj",
"fieldId": "12sdf45-78sfg52-dfjhjd"
}]
}
I want JSON Array and JSON Object separately and output should be like:
JSONArray
"Fields":[{ "objectId": "1234-56789-asdv",
"fieldId": "1245-7852-dhjd"},{
"objectId": "1234-56hgjgh789-hjjhj",
"fieldId": "12sdf45-78sfg52-dfjhjd"}]
and JSON Object should be like:
{
"messageName": "ReportCard",
"orgId": "Org1",
"comment": true
}
its pretty simple if you know java JSON API
String jsonString="{
"messageName": "ReportCard",
"orgId": "Org1",
"comment": true,
"Fields": [{
"objectId": "1234-56789-asdv",
"fieldId": "1245-7852-dhjd"
},
{
"objectId": "1234-56hgjgh789-hjjhj",
"fieldId": "12sdf45-78sfg52-dfjhjd"
}]
}"
JSONObject jObject= new JSONObject(jsonString);
JSONObject jo = new JSONObject(); //creating new Jobject
// putting data to JSONObject
jo.put("messageName", jObject.getString("messageName").toString());
jo.put("orgId", jObject.getString("orgId").toString());
jo.put("comment", jObject.getString("comment").toString());
JSONArray Fields= jObject.getJSONArray("Fields");//extract field array
JSONArray ja = new JSONArray(); //creating new json array.
int Arraylength = Fields.length();
for(int i=0;i<Arraylength;i++)
{
Map m = new LinkedHashMap(2);
JSONObject ArrayjObj = Fields.getJSONObject(i);
m.put("objectId", ArrayjObj.getString("objectId").toString());
m.put("fieldId", ArrayjObj.getString("fieldId").toString());
// adding map to list
ja.add(m);
}
JSONObject fieldsObj = new JSONObject();
fieldsObj.put("Fields", ja); // Fields Array Created
for JSON api refer this
you can fetch particular values as per keys into a json object and rest into a separate json array
String strJSON =" {\"id\":\"12\",\"messageName\":\"ReportCard\" , \"Fields\":[{\"objectId\": \"1234-56789-asdv\", \"fieldId\": \"1245-7852-dhjd\"},{\"objectId\": \"1234-56hgjgh789-hjjhj\", \"fieldId\": \"12sdf45-78sfg52-dfjhjd\"}] }";
JSONArray ja = new JSONArray();
JSONObject jo1= new JSONObject();
JSONObject jo= new JSONObject(strJSON);
ja= jo.getJSONArray( "Fields");
jo1.put("messageName",jo.get(messageName));
jo1.put("orgId",jo.get(orgId));

Parsing JSON array if I don't know array names

I've got this JSON file. But what to do if I dont know array names (First, Second). How to parse this file in android?
Thanx
{
"First": [
"Test1",
"Test2",
"Test3",
"Test4",
"Test5"
],
"Second": [
"Test1",
"Test2"
] }
JSON you're working with already is an array. So, don't construct an instance of JSONObject; use a JSONArray. This should suffice:
JSONArray jsonArray = new JSONArray(result);
for(int i=0;i<jsonArray.length();i++){
JSONObject e = jsonArray.getJSONObject(i);
String ex = jsonArray.getString("")
}

get values of array within array json in java

I need to get the values of the array "q1" which in array "questions", the arrays is json, and i need the values in java android.
{
"questions": [
{
"q1": [
"what my name?",
"a",
"b",
"c",
"Mac"
],
"q2": [
"what my age?",
"1",
"34",
"80",
"3"
]
}
]
}
Here I am answering your question to solve your problem but My friend you need to study first about json parsing.
Suggestion :
You can find example of it here :
http://primalpappachan.com/android/2010/06/05/parsing-json-in-android/
Answer :
JSONObject jresonseobj = response.getjObj();
JSONObject jobj;
JSONArray jsonArray = new JSONArray(jresonseobj.getString("questions"));
for (int i = 0; i < jsonArray.length(); i++)
{
jobj = jsonArray.getJSONObject(i);
// parse inner json here.
}

Android - How to parse JSONObject and JSONArrays from api.rottentomatoes

so, there's this JSON code. Im trying to get the "abridged_cast".
but its complicated.
its JSONObject
inside JSONArray onside jSONObject Inside JsonArray....
{
"total": 591,
"movies": [
{
"title": "Jack and Jill",
"year": 2011,
"runtime": "",
"release_dates": {
"theater": "2011-11-11"
},
"ratings": {
"critics_score": -1,
"audience_score": 90
},
"synopsis": "",
"posters": {
"thumbnail": "",
"profile": "",
"detailed": "",
"original": ""
},
"abridged_cast": [
{
"name": "Al Pacino",
"characters": []
},
{
"name": "Adam Sandler",
"characters": []
},
{
"name": "Katie Holmes",
"characters": []
}
],
"links": {
"self": "",
"alternate": ""
}
}
],
"links": {
"self": "",
"next": ""
},
"link_template": ""
}
this is my code for getting "title" and "year"
if (response != null) {
try {
// convert the String response to a JSON object,
// because JSON is the response format Rotten Tomatoes uses
JSONObject jsonResponse = new JSONObject(response);
// fetch the array of movies in the response
JSONArray movies = jsonResponse.getJSONArray("movies");
// add each movie's title to an array
movieTitles = new String[movies.length()];
for (int i = 0; i < movies.length(); i++) {
JSONObject movie = movies.getJSONObject(i);
movieTitles[i] = movie.getString("title");
}
hope someone would help me because i cant figure out how to get the abridged_cast"
movies contains an array of "movie" objects. Each one of those objects contains a field abridged_cast that is an array of (let's call them "cast member") objects.
If you're not going to map to a POJO and instead are going through the JSON, you simply need to get that array in your loop after getting movie, and get each "cast member" object from that array in the same manner using another loop.
...
JSONArray cast = movie.getJSONArray("abridged_cast");
for (int j = 0; j < cast.length(); j++) {
JSONObject castMember = cast.getJSONObject(j);
...
}
Edit from comments: Your original question involved how to extract the information from the JSON you have; the above code explains that. It now seems like you're asking a more fundamental programming question around how to use it.
If you're going to use the included org.json classes that come with Android, you now know how to access the information in the returned JSON object. And you could write methods around the parsed JSONObject to access the data as-is using the objects and methods from the json.org package. For example, you could write a "getMovie()" method that took the name of the movie as a string and searched that "movies" array for the right one and returned it as a JSONObject.
Normally you would create classes in Java that encapsulate the data returned in that JSON and use data structures that lend themselves to your access patterns (For example, a Map that conatained all the movies using their names as keys). Using the org.json classes you'll have to instantiate those objects and populate them manually as you parse the JSON like you're doing in your question. If you used either the Gson or Jackson JSON parsing libraries they are capable of taking the JSON you have and mapping all the data to the classes your create and returning them in a single call.
try {
String Movie = null;
String abridged = null;
JSONArray jsonResponse = new JSONArray(response);
for (int i = 0; i< jsonResponse.length(); i++) {
Movie = jsonResponse.getJSONObject(i).getString("movies").toString();
System.out.println("movies="+Movie);
abridged = jsonResponse.getJSONObject(i).getString("abridged_cast").toString();
}
JSONArray jArray = new JSONArray(Movie);
for (int i = 0; i< jArray.length(); i++) {
String title = jArray.getJSONObject(i).getString("title").toString();
System.out.println("title="+title);
}
JSONArray jabridgeArray = new JSONArray(abridged);
for (int i = 0; i< jabridgeArray.length(); i++) {
String title = jabridgeArray.getJSONObject(i).getString("name").toString();
System.out.println("title="+title);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

Jsonobject and Jsonarray management In Iteration

I am trying to send the details of Usrs and its items with json. But at time of json genertion, with iterated jsonarry with json object, i stuck t middle.how to manage Jsonrray and JsonObject for below given Iterated data.
{
"Data":
{
["user":1],
"items":
[{"item":1},{"item":2},{"item":3},{"item":4}]
},
{
["user":2],
"items":
[{"item":11},{"item":2},{"item":3},{"item":4}]
},
{
["user":3],
"items":
[{"item":11},{"item":2},{"item":3},{"item":4}]
},
}
I am not sure, whether above given structure is perfect or not?
if perfect then how can I retrieve particular users 4th item?
I feel bad while writing (non-challenging) code for you, but I had my IDE open, and waiting for coffee. So, code for you.
String s = "{\"Data\":[{\"user\":1,\"items\":[{\"item\":1},{\"item\":2},{\"item\":3},{\"item\":4}]},{\"user\":2,\"items\":[{\"item\":11},{\"item\":2},{\"item\":3},{\"item\":4}]},{\"user\":3,\"items\":[{\"item\":11},{\"item\":2},{\"item\":3},{\"item\":4}]}]}";
JSONObject json = new JSONObject(s);
JSONArray data = json.getJSONArray("Data");
for(int i=0; i< data.length(); i++){
JSONObject userData = data.getJSONObject(i);
if(userData.getInt("user") ==2 ){
JSONArray items = userData.getJSONArray("items");
JSONObject item = items.getJSONObject(3);
System.out.println("item#4: " + item.getInt("item"));
}
}
The correct JSON for you is
{
"Data":[
{
"user":1,
"items":
[{"item":1},{"item":2},{"item":3},{"item":4}]
},
{
"user":2,
"items":
[{"item":11},{"item":2},{"item":3},{"item":4}]
},
{
"user":3,
"items":
[{"item":11},{"item":2},{"item":3},{"item":4}]
}
]
}

Categories

Resources