Jsonobject and Jsonarray management In Iteration - java

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}]
}
]
}

Related

Cucumber:Assert values irrespective of Index

I am working on updating functional test suites using Cucumber feature file.The issue my output is an array which is not sorted.Index of the object may change.
Array:
[{
"id": "12",
"name": "Something"
},
{
"id": "13",
"name": "Another Something"
}
]
Here I wanna assert name when Id=13 only.Any help would be appreciated.
The Json is list of objects within an Array so you need parse them and validate the each Object. You can do like below,
Code:
JSONArray jsonArray = new JSONArray(JsonAsString);
JSONObject jsonObject;
for (int i = 0; i < jsonArray.length(); i++) {
jsonObject = new JSONObject(jsonArray.get(i).toString());
if (jsonObject.get("id").toString().equalsIgnoreCase("13")) {
System.out.println("Name: " + jsonObject.get("name"));
//do your thing...
}
}
Output:
Name: Another Something

How to parse this json in android studio?

{
"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

How to get data from JSONobject and display it into a listview?

This is my JSON
{
"data": [
{
"id": 1,
"Name": "Choc Cake",
"Image": "1.jpg",
"Category": "Meal",
"Method": "",
"Ingredients": [
{
"name": "1 Cup Ice"
},
{
"name": "1 Bag Beans"
}
]
},
{
"id": 2,
"Name": "Ice Cake",
"Image": "dfdsfdsfsdfdfdsf.jpg",
"Category": "Meal",
"Method": "",
"Ingredients": [
{
"name": "1 Cup Ice"
}
]
}
]
}
Now I am trying to display it into a listView how would I do that this is what i have right now (for testing purposes i am just trying to display all the names in a toast)
JSONObject jsonObj = new JSONObject(jsonStr);
int length = jsonObj .length();
for(int i=0; i<length; i++) {
Toast.makeText(this, jsonObj.getJSONArray("data").
getJSONObject(i).getString("Name"), Toast.LENGTH_LONG).show();
}
The Above code only display one name and not multiple names. How can I make it for multiple names?
Take a look this code snippet
//getting whole json string
JSONObject jsonObj = new JSONObject(jsonStr);
//extracting data array from json string
JSONArray ja_data = jsonObj.getJSONArray("data");
int length = jsonObj .length();
//loop to get all json objects from data json array
for(int i=0; i<length; i++)
{
JSONObject jObj = ja_data.getJSONObject(i);
Toast.makeText(this, jObj.getString("Name").toString(), Toast.LENGTH_LONG).show();
// getting inner array Ingredients
JSONArray ja = jObj.getJSONArray("Ingredients");
int len = ja.length();
// getting json objects from Ingredients json array
for(int j=0; j<len; j++)
{
JSONObject json = ja.getJSONObject(j);
Toast.makeText(this, json.getString("name").toString(), Toast.LENGTH_LONG).show();
}
}
I recommend to use 'Log' instead using 'Toast'.
If any confusion or query let me know, i will try my best to resolve it.
If answer is satisfiable please mark it as correct answer.
Happy coding!
Thanks
You are getting the length of JSONObject, but you should get the length of JSONArray inside that JSONObject in order to iterate though json array items.
int length = jsonObj.getJSONArray("data").size()
I think you are guessing it wrong. Look closely you have a Json in that you have array which is JsonArray with the name/key "data"
then in that you can get it and traverse it index by index. For you I am providing you a road map so that things make easy for you conceptually
Make a model class which may able to store the values as you are getting in response of your api or in this json respone.
Take an array of type of your model class to store values
Now you can add for loop to save values or you can parse and save your jason array into your array you made to handle the jasonarray
this is easily be understand by this link and this is a working example to parse the json array and to show in your list view. You have nothing to worry about after reading these two links.
get your result from URL where your json is and store to any variable (result here) , then decode it i am showing below,
try this , it may give you some hint , i have not tried but may help you
JSONObject jsonObject = new JSONObject(result);
JSONArray jsonArray = jsonObject.optJSONArray("data");
if (jsonArray != null) {
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObjects = jsonArray.optJSONObject(i);
int id = jsonObjects.optInt("id");
String varMessage = jsonObjects.optString("varMessage");
String Image = jsonObjects.optString("Image");
String Category = jsonObjects.optString("Category");
String Method = jsonObjects.optString("Method");
JSONArray jsonArrayIngredients = jsonObject.optJSONArray("Ingredients");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObjects = jsonArray.optJSONObject(i);
String name = jsonObjects.optString("name");
}
}
}

Accessing json string in java and creating hashmap Android

I have a JSON string and I am trying to retrieve information from it. Json String looks like this.
JSON STRING :
{
"information": {
"device": {
"id": 0
},
"user": {
"id": 0
},
"data": [
{
"datum": {
"id": "00GF001",
"history_id": "9992BH",
"name": "abc",
"marks": 57,
"class": "B",
"type": "Student"
}
},
{
"datum": {
"id": "72BA9585",
"history_id": "78NAH2",
"name": "ndnmanet",
"marks": 70,
"class": "B",
"type": "Student"
}
},
{
"datum": {
"id": "69AHH85",
"history_id": "NN00E3006",
"name": "kit",
"department": "EF003",
"class": "A",
"type": "Employee"
}
},
{
"datum": {
"id": "09HL543",
"history_id": "34QWFTA",
"name": "jeff",
"department": "BH004",
"class": "A1",
"type": "Employee_HR"
}
}
]
}
}
I am trying to access data JSONArray and respective Datum from it. I differentiated each datum as per type such as student, employee etc and push information in hashmap.
I successfully did it in javascript but in Java I am struggle abit.
When I am trying to access JSONArray it throws exception
try {
JSONObject data = new JSONObject(dataInfo);
// Log.d(TAG, "CHECK"+data.toString());
JSONObject info = data.optJSONObject("information");
if(info.getJSONArray("data").getString(0).equals("Student") > 0) //exception here
Log.d(TAG, "Data"+ data.getJSONArray("data").length()); //exception here too
for(int m = 0; m < data.length(); m++){
// for(int s = 0; s < data[m].ge)
}
} catch (JSONException j){
j.printStackTrace();
}
Any pointers to create hashmap respective type I have. Appreciated
If you're trying to access the type field of a datum object, you'll want something like this:
JSONObject data = new JSONObject(dataInfo); // get the entire JSON into an object
JSONObject info = data.getJSONObject("information"); // get the 'information' object
JSONArray dataArray = info.getJSONArray("data"); // get the 'data' array
for (int i = 0; i < dataArray.length(); i++) {
// foreach element in the 'data' array
JSONObject dataObj = dataArray.getJSONObject(i); // get the object from the array
JSONObject datum = dataObj.getJSONObject("datum"); // get the 'datum' object
String type = datum.getString("type"); // get the 'type' string
if ("Student".equals(type)) {
// do your processing for 'Student' here
}
}
Note that you'll have to deal with exception handling, bad data, etc. This code just shows you the basics of how to get at the data that you're looking for. I separated each individual step into its own line of code so that I could clearly comment what is happening at each step, but you could combine some of the steps into a single line of code if that is easier for you.
if dataInfo is the json you posted, then you have to access information and from information, you can access data:
JSONObject data = new JSONObject(dataInfo);
JSONObject info = data.optJSONObject("information");
if (info != null) {
JSONArray dataArray = info.optJSONArray("data")
}

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();
}

Categories

Resources