problem in json parsing in android app - android

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.

Related

How to fetch multilevel JSON using volley?

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

How to parse json array of objects with retrofit which has different data types for same key

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

how check is the json Array available and exist?

I'm loading a json array in my app.but i need to know if the json array is exist or not? because if the json array isn't exist, the app will crash.
for example, I have this json:
{
"music1":
[
{
"art":"",
"artist":"",
"music":"",
"flag":"",
"text":"",
"level":""
},
{
"art":"",
"artist":"",
"music":"",
"flag":"",
"text":"",
"level":""
},
]
}
and I want to know is there any json object named "music1" in my code or not, and then if there was I want to get the json array and show it in a list in my android app.
I'm looking forward a hero that could help me!
I wish this explanation would fit in a comment.
Anyway:
{
"music1":
[
{
"art":"",
"artist":"",
"music":"",
"flag":"",
"text":"",
"level":""
},
{
"art":"",
"artist":"",
"music":"",
"flag":"",
"text":"",
"level":""
}
]
}
Let call the above json object o.
So to check if o has music1, all you need to check is write the following line:
if(o.has("music1")){
JSONArray array= o.getJSONArray("music1");
}
Then you extract the objects of the json array :
for(int i=0;i<array.length();i++){
array.getJSONObject(i);
}
Check the availability of field:
if(jsonObj.has("music1")){
//yes
}
or this case:
JSONArray mJSONArray = jsonObj.optJSONArray("nmusic1");
If array is not available mJSONArray will be null

How to search in JSON and return search results in activity

I am parsing a JSON in my activity to display both text and images in a gridView.However i would like to try to add search functionality on this JSON and display the results on the activity.
For example consider a JSON script on an online server like this:
[
{
"title": "Ongata Rongai",
"image": "http://snapt.t15.org/melanie/real_estates/images/house1.jpg",
"rating": 5 500 000,
"releaseYear": 2014,
"genre": ["Spacious open lounge and kitchen"]
},
{
"title": "Kisumu",
"image": "http://snapt.t15.org/melanie/real_estates/images/house2.jpg",
"rating": 1 700 000,
"releaseYear": 2014,
"genre": ["high end townhouse."]
},
{
"title": "Mombasa",
"image": "http://snapt.t15.org/melanie/real_estates/images/house3.jpg",
"rating": 68 000,
"releaseYear": 2014,
"genre": ["Its fully fitted kitchedn pantry with a beautyful backyard."]
}
]
I would like to implement search of title like Kisumu and the result to be displayed will be from this part only so that i parse this alone:
[
{
"title": "Kisumu",
"image": "http://snapt.t15.org/melanie/real_estates/images/house2.jpg",
"rating": 1 700 000,
"releaseYear": 2014,
"genre": ["high end townhouse."]
}
]
Is there a way of achieving the above?
I am open to ideas and suggestions and any help will be appreciated.
You can't search json directly. Convert the json to List Java classes. Then use Java API like Predicate to find necessary java class that satisfy your condition. For eg: Title as Kusumu as you asked.
Which will limit the list of classes to one that satisfy the condition. Then convert the java class back to json if you need Json.
Note: You can use GSON for easy class <-> json conversion
UPDATE
For converting Json to Java classes
List<ModelClass> models = new Gson().fromJson(yourJsonString, ModelClass.java);
Then using predicate
public static Predicate<ModelClass> isHavingTitle() {
return p -> p.getTitle().contains("Kusumu");
}
In Java 8 predicate filtering can be done like below in other case you can just google it. This is a sample
public static List<ModelClass> filterEmployees (List< ModelClass > models, Predicate< ModelClass > predicate) {
return models.stream().filter( predicate ).collect(Collectors.<ModelClass>toList());
}
I didn't compile any of this :)
String filteredJson = new Gson().toJson(models);
this method give resualt of server and title as you want and returns search result as JSONObject
private JSONObject SearchMethod(String result,String Key)
{
//result is your server response
//Key is Kisumu
JSONArray json = new JSONArray(result);
for(int i=0;i<json.length();i++){
JSONObject e = json.getJSONObject(i);
if(e.c.getString("title").contains(Key))
return e ;
}
return null;
}

(Android) Java: JSON Parsing

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.

Categories

Resources