I found a lot of tutorials here, how to parse JSON Data of an JSON Array.
But my JSON File is a little bit complicate (for me). It has the following structure:
JSON File (excerpt)
{
"data": {
"schedule_id": {
"12": {
"name": "CP",
"d_id": [
"7"
]
},
"17": {
"name": "WT",
"d_id": [
"88",
"14"
]
}
}
}
}
Java Code (excerpt)
Info: I've parsed the json into "json" using HTTP GET in another Activity.
JSONObject dataJsonData = json.getJSONObject("data").getJSONObject("schedule_id");
Now I would parse through the ids using a "for"-loop:
ArrayList<String> parsedNameList = new ArrayList<String>();
for (int i = 0; i < idontknow; i++) {
String s = new Integer(i).toString();
parsedNameList.add(dateJsonData.getJSONObject(i).getString("name"));
}
This would add each value of "name" to the ArrayList.
But there are 2 problems:
1. The "schedule_id"s are messed up and incomplete. For example, there is no id "0" and, like in given json, the ids "13, 14, 15, 16" are missing.
2. The "schedule_id"s will be changed every day and will be mixed.
So I don't think, that I can use the predefined integer "i" because some integers aren't a "schedule_id". I could use this loop and would ignore empty entries in the ArrayList, but the JSON contains more than 200 ids - I think it would be more efficient, if there is another way to parse through this json.
I found some informations of the getJSONArray method, but the "d_id"s are Arrays - not the "schedule_ids".
Does anyone has an idea? Is there maybe a placeholder for the parameter of the getString method?
PS: Excuse my english, I'm from germany :)
I think this should work
Iterator keys = dataJsonData.keys();
while(keys.hasNext()) {
// loop to get the dynamic key
String currentDynamicKey = (String)keys.next();
// get the value of the dynamic key
String currentDynamicValue = dataJsonData .getString(currentDynamicKey);
parsedJsonList.add(currentDynamicValue );
}
Source: How to parse a dynamic JSON key in a Nested JSON result?
According to your context, it is better to change the json structure,if you have access to web service.
Request for json structure to be like this,
{
"data":{
"schedule":[
{
"id":12,
"name":"CP",
"d_id":[
"7"
]
},
{
"id":12,
"name":"CP",
"d_id":[
"7",
"88"
]
},
{
"id":200,
"name":"AT",
"d_id":[
"7",
"88"
]
}
]
}
}
Otherwise too much iteration can slow down you CPU.
Related
My JSON Example where i am willing to get data from every "show" Array
{
"score":17.873907,
"show":{
"id":139,
"url":"http://www.tvmaze.com/shows/139/girls",
"name":"Girls",
"type":"Scripted",
"language":"English",
"genres":[
"Drama",
"Romance"
],
"status":"Ended",
"runtime":30,
"premiered":"2012-04-15",
"officialSite":"http://www.hbo.com/girls",
"schedule":{
"time":"22:00",
"days":[
"Sunday"
]
},
"rating":{
"average":6.7
},
"weight":81,
"network":{
"id":8,
"name":"HBO",
"country":{
"name":"United States",
"code":"US",
"timezone":"America/New_York"
}
},
"webChannel":null,
"externals":{
"tvrage":30124,
"thetvdb":220411,
"imdb":"tt1723816"
},
"image":{
"medium":"http://static.tvmaze.com/uploads/images/medium_portrait/31/78286.jpg",
"original":"http://static.tvmaze.com/uploads/images/original_untouched/31/78286.jpg"
},
"summary":"<p>This Emmy winning series is a comic look at the assorted humiliations and rare triumphs of a group of girls in their 20s.</p>",
"updated":1600633829,
"_links":{
"self":{
"href":"http://api.tvmaze.com/shows/139"
},
"previousepisode":{
"href":"http://api.tvmaze.com/episodes/1079686"
}
}
}
}
The Request Code I am using which is giving me the response nicely but i cannot parse the response to JSONObject
Error Showing
org.json.JSONException: Value show of type java.lang.String cannot be
converted to JSONObject
When you are passing JSONObject("show") , it is trying to convert 'show' string to json Obviously it isn't json stirng so it is throwing error;
It should be something like :
JSONObject obj = new JSONObject(response);
JSONObject obj_show= obj.getJSONObject("show"));
Log.d("show",obj_show.getJSONObject("show").toString());
The Solution Was "I Used Nested Model Class to Load Data, and that worked like a charm!"
I am using gson lib to create json from objects. Backend developers are asking to create all values should be in "" quotes event int/long/boolean fields. For example my json looks like that:
{
"age": 26,
"email": "norman#futurestud.io",
"isDeveloper": true,
"name": "Norman"
}
-> i need the following format:
{
"age": "26",
"email": "norman#futurestud.io",
"isDeveloper": "true",
"name": "Norman"
}
Should i change all my fields from int to String or is there any way to do that? Thanks in advance!
To achieve this only way is to store Int as String and then converting the Data class to json String.As Gson use auto typecasting, you can't tell Gson to convert int to String and give you json.
Create the POJO according to your output json that is the only go.
Your code is JavaScript object literal, not a JSON.
Well try this out!
var obj = {"age": 26,"email": "norman#futurestud.io", "isDeveloper":
true, "name":
"Norman"};
for (var k in obj) {
if (obj.hasOwnProperty(k))
{
obj[k] = String(obj[k]);
}
}
I am getting a json array in API response which has different data types (String, Integer and Array) in same key (value) but getting error while parsing them with Retrofit:
{
"custom_attributes": [
{
"attribute_code": "description",
"value": "<p>Product Features:</p>\r\n<ul>\r\n<li>100% cotton</li>\r\n<li>Round neck</li>\r\n<li>Short sleeve</li>\r\n<li>Plastisol printing technique</li>\r\n<li>Small label on side of sleeve</li>\r\n</ul>"
},
{
"attribute_code": "short_description",
"value": "<p>100% cotton round neck short sleeve tee with plastisol printing technique</p>"
},
{
"attribute_code": "category_ids",
"value": [
"3",
"125"
]
},
{
"attribute_code": "special_price",
"value": true
},
{
"attribute_code": "size",
"value": 4
}
]
}
I can't understand what is the need of keeping your JSON format like this.
According json.org:
JSON is built on two structures:
• A collection of name/value pairs. In various languages, this is realized as an object, record, struct, dictionary, hash table, keyed list, or associative array.
• An ordered list of values. In most languages, this is realized as an array, vector, list, or sequence.
Tell me your requirement i will update your JSON and this problem will be solved once you will start getting updated JSON from erver.
Firstly store response in string like this
String response =apiresponse;
Then try this parsing methood without any thirdparty
get jsonobject from string response
JSONObject object=new JSONObject(response);
get jsonarray from json object
JSONArray jsonArray=object.getJSONArray("custom_attributes");
iterate json array till its length
for(int i=0;i<jsonArray.length;i++){
JSONObject newobject=jsonArray.getJSONObject(i);
Boolean valueBoolean;
String valueString;
String attribute_code=newObject.getString("attribute_code");
Object value=newObject.get("value");// get **value** key data in object
now check datatype of value key
if(value instanceof String){
valueString=value.toString(); //if value found string store in in value String
}else if(value instanceof Boolean){
valueBoolean=(Boolean)value; //if value found Boolean store it in valueBoolean
}
}
In the last its upto you , you may simply create a custom arraylist and save all details with datatype key
I've written some code to parse the Google Distance Matrix JSON response received by my Android program. The only piece of data I'm interested in is in the "distance" "value" node.
My code works, but it seems like there must be an easier way to do this. The distance value node is nested pretty deep inside the JSON, but is it really necessary to go through every layer of the JSON to get to the field you want?
Here's my JSON response:
{
"destination_addresses" : [
"5660 Baltimore National Pike, Ingleside Shopping Center, Catonsville, MD 21228, USA"
],
"origin_addresses" : [ "Hilltop Cir, Baltimore, MD 21250, USA" ],
"rows" : [
{
"elements" : [
{
"distance" : {
"text" : "3.1 mi",
"value" : 4922 <--THE FIELD I WANT TO EXTRACT
},
"duration" : {
"text" : "11 mins",
"value" : 666
},
"status" : "OK"
}
]
}
],
"status" : "OK"
}
And here is the code I used to pull out the distance value:
private double extractDistance(JSONObject json) {
JSONArray rowsArray = null;
double distanceInMiles = -1;
try {
// Getting Array of Distance Matrix Results
rowsArray = json.getJSONArray("rows");
JSONObject rowsObject = rowsArray.getJSONObject(0);//only one element in this array
JSONArray elementsArray = rowsObject.getJSONArray("elements");
JSONObject elementsObject = elementsArray.getJSONObject(0);//only one element in this array
JSONObject distanceObject = elementsObject.getJSONObject("distance");
distanceInMiles = (distanceObject.getDouble("value"))/1609.344; //distance in meters converted to miles
}
catch (JSONException e) {
e.printStackTrace();
}
return distanceInMiles;
}
Thanks!
I recommend you GSON (http://code.google.com/p/google-gson/) which parse the JSON text into a java class instance, and can convert the class instance to JSON text
Jackson is another good third party parser http://jackson.codehaus.org/. Looks like there's a comparison here, http://www.cowtowncoder.com/blog/archives/2009/09/entry_326.html.
Here's an example traversing using a tree, not sure if it qualifies as easier then what you are already doing, http://wiki.fasterxml.com/JacksonTreeModel
Unless you want to go into writing a custom regular expression to search the json string, yes that's going to be the best way of accessing it (and the easiest). Is there a reason you feel you need to access it 'more efficiently'?
If you are willing to include a third party library you might check out http://code.google.com/p/json-path/ .
I know what you feel right now, I had / have same issues with JSON parsing on android where we dont have #getValueforKey kind of features which is embedded on iOS, Even its so obivious google should realize it now, But there is good work done on Gson lib., look for Google Gson Here for easy way to parse json
Here is nice tute : Gson tute
in my app when i hit an url i am getting a return data as an json array. it is as follows
{"Status":[{ "img_path": "http://xxxxxxxxxxxxxx.com/images/thumb140/1316145577.jpg",
"img_path": "http://xxxxxxxxxxxxxx.com/images/thumb140/1316146270.jpg",
"img_path": "http://xxxxxxxxxxxxxx.com/images/thumb140/1316146473.jpg",
"img_path": "http://xxxxxxxxxxxxxx.com/images/thumb140/1316147003.jpg" } ]}
From the above result i am trying to parse out the urls and i am trying to store it in an array list. Following is my code
try{
JSONArray get_post_status = json.getJSONArray("Status");
for (int i = 0; i < get_post_status.length(); i++) {
JSONObject e = get_post_status.getJSONObject(i);
if(e.equals("img_path"))
{
Get_post_image_array.add(e.getString("img_path"));
}
}
But in my arraylist i am getting only the last url from the result. How to get all the urls in the arraylist.
Pls help me.......
The returned JSON is invalid.
Shortening the data, looking only at the structure:
{
"Status":
[
{
"img_path": "a",
"img_path": "b",
"img_path": "c",
"img_path": "d"
}
]
}
We can see that the array (enclosed in []) only contains one element; the object enclosed by {}. This object has several instances of the same key, "img_path". This is not valid. Your parser apparently ends up with keeping only the last instance of it.
The JSON ought to look more like this:
{
"Status":
[
"a",
"b",
"c",
"d"
]
}
Your JSON is invalid.
{"Status": [ {"img_path": "blah, blah"}, {"img_path": "blah2, blah3"}]}
is what you want. Essentially, you were setting the same key in an object over and over, not creating a list of objects.