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")
}
Related
I have received a json string like so:
{
"data": [
{
"name": "Order",
"value": "2"
},
{
"name": "Address",
"value": "182"
},
{
"name": "DNS",
"value": "null"
},
{
"name": "SSID",
"value": "work"
},
{
"name": "Protocol",
"value": "0"
},
{
"name": "Key",
"value": ""
},
{
"name": "carrier",
"value": "undefined"
},
{
"name": "SSH",
"value": "1"
},
{
"name": "ntp_addr",
"value": ""
},
{
"name": "Name",
"value": ""
}
]
}
I used stringify on an html response and this is what I have to parse. As you can see, it is pretty redundant; I would much rather { "Order":"2" } than { "name":"Order","value":"2" } ... So an array of name-value pairs, instead of an array of objects.
Is there a way I can dynamically format this response so that it will be easier to parse?
What 'd like is to be able to say:
JSONObject jsonObject = new JSONObject(jsonResponse);
JSONArray data = jsonObject.getJSONArray("data");
for (int i = 0; i < data.length(); i++) {
JSONObject dataObject = data.getJSONObject(i);
String order = dataObject.getString("Order");
String address = dataObject.getString("Address");
// etc...
}
But the current format makes it almost impossible to parse. I'd need loops within loops.
I'd like to use com.google.gson library. And this response easy to parse with it:
private final JsonParser PARSER = new JsonParser();
public void parse(String jsonString) {
JsonObject dataObject = PARSER.parse(jsonString).getAsJsonObject();
JsonArray dataArray = dataObject.get("data").getAsJsonArray();
dataArray.iterator().forEachRemaining(element -> {
String name = element.getAsJsonObject().get("name").getAsString();
String value = element.getAsJsonObject().get("value").getAsString();
}
}
Or you can simply use TypeAdapters for json deserialization directly in the object.
Something like this should do the trick
JSONObject jsonObject = new JSONObject(jsonResponse);
JSONArray data = jsonObject.getJSONArray("data");
JSONObject simplifiedDataObject = new JSONObject();
for (int i = 0; i < data.length(); i++) {
JSONObject dataField = data.getJSONObject(i);
simplifiedDataObject.put(dataField.getString("name"), dataField.get("value"));
}
You just iterate over each element in data, use the name field as the field on a new JSONObject and simply retrieve the value using the value key.
I have complex API that i parse and show in list view,I will be struggle to parse JSONArray.Here i will be in struggle following Json Array which is inside the posts json object "tags_name": ["Activities"],,some object it will come like "tags_name": [], this.Kindly review my question. My API and code is below. Presently i will implemented parsing code with model class. Once fix this issue i have to write list view coding please help me. May be my question formation is in silly way. please it look like means give some suggestion to frame question. Thanks in Advance.
MyAPI:
{
"status": true,
"nextpage": 0,
"count": 31,
"data": {
"postlist": [{
"posts": {},
"tags_name": ["Activities"],
"images_count": 3,
"images": [],
"post_user": [],
"is_encourage_user": true,
"encourage_feed_id": "1093"
},
{
"posts": {"id": "4647"},
"tags_name": [],
"images_count": 0,
"images": [],
"post_user": [],
"is_encourage_user": true,
"encourage_feed_id": "992"
}
]
},
"token": "wqeeqweqweqweqweqsfsdfsdf"
}
My Method for Parsing
private void parsingPostValues(String responseStatus) throws JSONException {
JSONObject responseObject = new JSONObject(responseStatus);
JSONObject datObject = responseObject.getJSONObject("data");
JSONArray postArr = new JSONArray(datObject.getString("postlist"));
for (int i = 0; i < postArr.length(); i++) {
JSONObject tempPostObject = postArr.getJSONObject(i);
JSONObject postObject = tempPostObject.getJSONObject("posts");
//setTag Array- this is the functional area i'm in bottle-neck.
try {
JSONArray tagNameArr = tempPostObject.getJSONArray("tags_name");
//ArrayList<Bean> tagListdata = new ArrayList<Bean>(tagNameArr.length());
if (tagNameArr.length()>0) {
for (int tagInfo = 0; tagInfo < tagNameArr.length(); tagInfo++) {
// listdata.add(tagNameArr.get(i).toString());
String tagme = "";
//Bean tagBean = new Bean();
//tagBean.setTagsArray((tagme.isEmpty() ? tagNameArr.get(tagInfo).toString() : "null")); //tagBean.setTagsArray(tagNameArr.get(tagInfo).toString());
//tagListdata.add(tagBean);
//beanAccess.setTagsArray(tagNameArr.get(tagInfo));
System.out.println("Tags Array:"+tagInfo+":"+tagNameArr.get(tagInfo));
}
//beanAccess.setTagsArray(tagListdata);
}
} catch (Exception e) {
e.printStackTrace();
}
}
replace this
JSONArray postArr = new JSONArray(datObject.getString("postlist"));
To
JSONArray postArr = datObject.getJSONArray("postlist");
Replace
String imgCount = tempPostObject.getString("images_count");
String is_encourage_user = tempPostObject.getString("is_encourage_user");
To
String imgCount = postObject.getString("images_count");
String is_encourage_user = postObject.getString("is_encourage_user");
It will work for you.
I'm trying to get the value of a specific attribute in a JSON file but instead I get a row content of the array.
For example that's my JSON file:
{
"head": {
"vars": [ "type1" , "pred" , "type2" ]
} ,
"results": {
"bindings": [
{
"type1": { "type": "Collection" } ,
"type2": { "type": "has" } ,
"type3": { "type": "contributor" }
} ,
{
"type1": { "type": "Collection2" } ,
"type2": { "type": "has2" } ,
"type3": { "type": "contributor2" }
}
]
}
}
I want to get only the values of attribute "type3"
But my following code gets me all of them.
JSONObject obj = new JSONObject(json);
JSONObject results = obj.getJSONObject("results");
JSONArray bindings = results.getJSONArray("bindings");
for (int i=0; i<bindings.length(); i++)
{
JSONObject x = bindings.getJSONObject(i);
x.getJSONObject("type3");
}
I tried several approaches but it seems I'm doing it wrong.
I only want to get this : { "type": "contributor" }
Then get that value (roughly) like so
bindings.getJSONObject(0).getJSONObject("type3")
you can use JsonPath.read to get all Type3 values as list.
List value = JsonPath.read(bindings, "..type3");
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();
}
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}]
}
]
}