How to fetch multilevel JSON using volley? - android

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

Related

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 to show JSON parsed data in expandable listview?

I am using AndroidHive method to display a custom expandable listview. It has a static data inserted. but in my app , i am receiving a json data and i am unable to parse it in a way to display it inside the expandable listview.
JSON data I recieve is
{
"success": 1,
"Message": "User exist",
"category": [{
"major_item_id": "1",
"Major_item_name": "Cement"
}, {
"major_item_id": "15",
"Major_item_name": "Wire"
}],
"subcategory": [{
"major_item_id": "1",
"name_item":"abc1"
}, {
"major_item_id": "1",
"name_item":"pqrs2"
}, {
"major_item_id": "15",
"name_item":"lmn"
}, {
"major_item_id": "15",
"name_item":"xyz"
}]}
What I want to is an expandable listview in format :
Cement //listHeader
-abc1 // child items
-pqrs2 // child items
Wire
-lmn
-xyz
An JSON file consist of many components. Here is the table defining the components of an JSON file and their description
Array([)
In a JSON file , square bracket ([) represents a JSON array
Objects({)
In a JSON file, curly bracket ({) represents a JSON object
Key
A JSON object contains a key that is just a string. Pairs of key/value make up a JSON object
Value
Each key has a value that could be string , integer or double e.t.c
Each implementations are different according to the json format that you have been used. You can easily find too many examples on internet.
http://www.tutorialspoint.com/android/android_json_parser.htm
You can use Gson to convert the JSON to an object like this:
Gson gson = new Gson();
Type listType = new TypeToken<YourObject>() {}.getType();
YourObject obj = gson.fromJson(getCurrentChat(), listType);
Once you have the correct object you can use the corresponding values to update your ExpandableListView.

(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.

Need help in this Weird JSON

I have a JSON as below
{
"shippingGroupListJson":[
{
"lineId":123,
"shippedTo":{
"country":"US"
},
"cartons":1,
"group":"4",
"shipInscription":{
"municipalInscription":"",
"inscriptionType":"",
"stateInscription":"",
"suframaInscriptionNumber":"",
"inscriptionBranch":"",
"contributorClass":"",
"inscriptionDigit":"",
"inscriptionNumber":""
},
"shipCartonDetails":[
],
"shippedContact":{
"firstName":"Mjjkk",
"email":"nob#gmail.com",
"fax":"--",
"phone":"80-121",
"lastName":"Henry"
},
"mobilityShipStatus":"Not Yet Shipped",
"shipDate":"13 Dec 2014"
},
{
"lineId":0,
"shippedTo":[
],
"cartons":0,
"group":"5",
"shipInscription":[
],
"shipCartonDetails":[
],
"shippedContact":[
],
"mobilityShipStatus":"",
"shipDate":"",
"shipStatus":""
}
]
}
If you see in this above JSON in key "shippedTo", when there is value , I get a JSON Object and when no value is present then i get a Blank JSONArray.
I need to fix this issue. I cannot communicate with the service team to change this as they won't make changes to it. Can any one tell me how can i do the required changes.
I know this is not the rite way, but i need to do something..
I tried using String.replaceAll(oldChar,newChar);
You say you are using GSON, in which case JsonArray and JsonObject are both subclasses of JsonElement.
But you do not say if you are using the DOM or Streaming technique with GSON.
You should show your parsing code, or the class that's being automatically used for the parsing.
In the meantime, based on what you have said, I would define my shippedTo field in my class as an Object. That should parse correctly (if using DOM), and after that you can analyse exactly what you have in that field.
Instead of:
private MyCountryType shippedTo;
Have:
private Object shippedTo;
You could simply check its type at runtime i.e
JSONObject jsPar=new JSONObject(json_data);
JSONArray jsarrPar=js.getJSONArray("shippingGroupListJson");
for(int i=0;i<jsarrPar.size();i++){
JSONObject js= jsarrPar.getJSONObject(i);
if(js.get("shippedTo") instanceof JSONArray){
//Treat it as an array
}
else{
//Treat it as a single json object
}
}
Furthermore if you need it as an JSONObject immaterial of it being a single element then do this to get your customized string
JSONObject jsPar=new JSONObject(json_data);
JSONArray jsarrPar=js.getJSONArray("shippingGroupListJson");
for(int i=0;i<jsarrPar.size();i++){
JSONObject js= jsarrPar.getJSONObject(i);
JSONObject js=new JSONObject(json_data);
if(js.get("shippedTo") instanceof JSONArray){
js.put("shippedTo",new JSONObject()); //purge the original array with this new blank element
}
else{
//Do your normal stuff
}
}
String curmodstring=jsPar.toString();
Hope you get the general idea.

Parsing json file with gson

I have a problem creating a mapping for a json that i want to parse using json. It's very specific, its about a json file with a json array with objects in it.
my jsonfile starts like this:
[
{
"venue": {
"venue_seasons": [
{
"created_at": "2011-12-25T23:00:28Z",
"updated_at": "2011-12-28T15:13:53Z",
"start_timestamp": 1293840000,
"id": 337,
"end": "2011-12-24T00:00:00Z",
"enabled": true,
"start": "2011-01-01T00:00:00Z",
"season_openings": [ … ],
"end_timestamp": 1324684800
},
{ … }
],
"address": "someadress",
"city": "cityname",
"name": "name",
"created_at": "2011-03-31T07:55:33Z",
etcetera
}
"venue":{another venue
So first an array, than an object (venue) with a lot of objects in it (i removed most of them, because thats not important for my question), and some arrays (like season_openings).
My parsing code works like this, im using gson. The inputstream works fine.
Reader reader = new InputStreamReader(inputStream);
JsonResponse venueResponse = gson.fromJson(reader, JsonResponse.class);
List<Venues> results = venueResponse.venue;
with the class JsonResponse:
public class JsonResponse {
public List<Venues> venue;
}
and Venues.class:
public class Venues {
public List<VenueSeasons> venue_seasons;
#SerializedName("adress")
public String getAdress;
#SerializedName("city")
public String getCity;
#SerializedName("country")
public String getCountry; etcetera
}
But when i run this code i get an error:
Unable to start activity ComponentInfo{com.hera.android.JSON/com.hera.android.JSON.TestParser2Activity}: com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was BEGIN_ARRAY at line 1 column 2
Ofcourse i can read the error: it expects an objects but get an array. I varied a lot with different jsonresponse.class and even with putting the whole json array in a json object (what is not really a solution because i need to work with this type of jsonfile). But everytime i get this or a similar error.
I think I'm close to a solution, can anyone see what i just can't and give me a helping hand?
Thanks.
Try calling Gson like this:
List<Venues> venues = gson.fromJson(reader, new TypeToken<List<Venues>>() {}.getType());
This works because your JSON document is a List, not an object that has a list as one of its properties.

Categories

Resources