I am using Retrofit lib for API call in my Android application. My JSON is like this.
{"options": [
{
"type": "item",
"type_id": "19E9E453-64C6-41C9-BFB7-D6EFB8AF68B8",
"key": "ageRange",
"value": "Early 30s"
},
{
"type": "item",
"type_id": "19E9E453-64C6-41C9-BFB7-D6EFB8AF68B8",
"key": "colors",
"value": "Black, Red"
}
]}
Or
{"options": []}
My model code is:
#SerializedName("options")
#Expose
private ArrayList<OptionsDataModel> options;
So if options is not empty the code working fine but if options is empty I am getting error invalid item. So can any one help to solve this problem.
You can add a check in your response method for result.body != null before parsing your response to your object
Related
I am trying to fetch JSON Object which has 2 list object with the same name, but has a different value. The object list named "items", the first "items" has "products_title,product_image,link", and the second "items" has "article_title, article_image,link". How to write PODO ?
I've been trying to writes PODO, but even i try to change the model, it still does not work. I try the other REST API, for the example "https://jsonplaceholder.typicode.com/pothos" its working fine. But if i try used my JSON its getting error, i wonder how to write PODO ?
this is the JSON i am using :
{
"data": [
{
"section": "electronics",
"items": [
{
"product_name": "Cellphone",
"product_image": "cellphoneImage.png",
"link": "https://cellphone.html"
},
]
},
{
"section": "facts",
"section_title": "Title section",
"items": [
{
"article_title": "Facts",
"article_image": "https://www.facts.png",
"link": "https://www.facts.html"
},
]
}
]
}
This is my cart list and I'm converting into JSON object to send at the server
Map<String,dynamic> str={'cart':cartList};
cartitem = jsonEncode(str);
doing something like this but it is adding extra JSON object and this is invalid JSON form. then how can I remove extra JSON object.
{
{"cart":[
{
"cartid":2,
"pid":"342702",
"merchantId":"MER-07156",
"hashkey":"7087fea71afc963d6dc3fa04944008ec",
"productname":"Scheduling Product - Edit Please",
"product_image":"Scheduling Product - Edit Please",
"shipping_price":"0.00",
"state_tax_rate":"0.0",
"taxamt":"0.00",
"discountamt":"0.0",
"price":"10.00",
"pricewithattr":"17.00",
"quantity":"18",
"totalamount":"306.00",
"taxvalue":"0.0",
"attribute_array":"[{\"attributeid\":\"20796\",\"attributename\":\"Black\",\"groupname\":\"Color\",\"groupid\":\"3012\"},{\"attributeid\":\"20798\",\"attributename\":\"Silk\",\"groupname\":\"Cloth\",\"groupid\":\"3013\"},{\"attributeid\":\"20800\",\"attributename\":\"small\",\"groupname\":\"Size\",\"groupid\":\"3014\"}]",
"is_free":"0",
"is_payable_later":"0",
"isattrpresent":"1"
}
]
}}
Strange, because this code:
Map<String, dynamic> str = {
'cart': [1, 2, 3]
};
String cartitem = jsonEncode(str);
print(cartitem);
which does basically the same thing, produces valid json:
{"cart":[1,2,3]}
Try debugging by just json encoding one of the cart members, replacing the cart members by something simple (like an integer, above) until you find the issue.
Your JSON is not right structure.
Did you try to parse it any online converter?
You should remove { character before "cart" and remove } character the end of json.
I tried to debug and found that jsonEncode was adding an extra object so I converted cartiem into jsonEncode prior to adding into the map.
var cartitems2=cartList;
Map<String,dynamic> str={'"cart"':json.encode(cartitems2)};
cartitem = str.toString();
debugPrint('CART :-----${cartitem}');
Expected Result
{
"cart": [
{
"cartid": 22,
"pid": "342702",
"merchantId": "MER-07156",
"hashkey": "7087fea71afc963d6dc3fa04944008ec",
"productname": "Scheduling Product - Edit Please",
"product_image": "Scheduling Product - Edit Please",
"shipping_price": "0.00",
"state_tax_rate": "0.0",
"taxamt": "0.00",
"discountamt": "0.0",
"price": "10.00",
"pricewithattr": "26.00",
"quantity": "10",
"totalamount": "260.00",
"taxvalue": "0.0",
"attribute_array": [
{
"attributeid": "20794",
"attributename": "Red",
"groupname": "Color",
"groupid": "3012"
},
{
"attributeid": "20799",
"attributename": "Cotton",
"groupname": "Cloth",
"groupid": "3013"
},
{
"attributeid": "20800",
"attributename": "small",
"groupname": "Size",
"groupid": "3014"
}
],
"is_free": "0",
"is_payable_later": "0",
"isattrpresent": "1"
}
]
}
The JSON result for getUsers I get from the server looks like this:
{
"result": [
{
"meta": {
"rows": "3"
}
},
{
"items": [
{
"id": "1",
"name": "Steve",
"age": "30"
},
{
"id": "2",
"name": "Mary",
"age": "29"
},
{
"id": "3",
"name": "Bill",
"age": "58"
}
]
}
]
}
How can I deserialize it by GSON in my android app (I'm using retrofit)?
I can't imagine any wrapper classes because of the different object types in result.
Any help would be appreciated!
For good example
Converting JSON to Java
Other way, you can convert your json to a java object
Please use org.json library http://www.json.org/java/index.html
Then, for example
json = new JSONObject(YOUR_JSON).getJSONObject("result");
JSONArray items = data.getJSONArray("items");
String name = items.getJSONObject(0).getString("name");
You can write a TypeAdapter for a type that will be (de)serialized to(from) array. You can even make it generic, so it will work with type like Pair<A, B>. Here is an example for non-generic type: https://github.com/cakoose/json-tuple-databinding-examples/blob/master/java/src/GsonEntryCustomizer.java — it (de)serializes Entry to(from array).
Disclaimer — I have not written nor tested that code, but it seems legit.
If you only encounter such problem once (like in your example), you may not bother making it generic, just write TypeAdapter for your specific pair of 2 different classes. The reading code is quite straightforward:
in.beginArray();
SomeClass1 info1 = gson.getAdapter(SomeClass1.class).read(in);
SomeClass2 info2 = gson.getAdapter(SomeClass2.class).read(in);
in.endArray();
return new SomeContainerClass(info1, info2);
(see https://github.com/cakoose/json-tuple-databinding-examples/blob/master/java/src/GsonEntryCustomizer.java#L52)
I have been trying to wrap my head around how to parse nested objects and arrays with GSON, still stuck. How can I parse the nested items listed in the "results" array?
{
"item": {
"results": [
{
"__metadata": {
"url": "google.com",
"type": "website"
},
"listed": true,
"market": 225,
"town": "Toronto"
},
{
"__metadata": {
"url": "twitter.com",
"type": "website"
},
"listed": true,
"market": 225,
"town": "Calgary"
}
]
}
}
How can I easily do this with GSON within Android?
Thank you!
Android Studio
Download Plugin "GsonFormat"
Create your model class
Open Code->Generate->Gson
Paste your json click ok - if json is valid then it will convert the following json to java class (pojo)
Now create Gson object
Gson gson=new Gson();
Convert Json to java object
T obj = gson.fromJson(contents, tClass);
Now use this object "obj" to get values
I have an url,get and response given. I have to parse the JSON and show the locations in Map in android. I dont need you to code. I am new in JSON. please tell me some steps how i can do that. how should i start and which steps i should take?
Url: "Some url"
Sending data:
{
"tag": "getAvailableDriver",
"lat": 41.022348,
"lng": -91.966721
}
RESPONSE:
{
"posts": [
{
"success": "1",
"driver": [
{
"id": "768",
"lat": "41.022848",
"lon": "-91.966884",
"recorded_datetime": "2014-07-20 20:18:03",
"user_id": "403",
"cabbi_state": "OnJob",
"vehicleType": "Black Cab",
"driver_name": "black cab driver",
"pic_name": "userimage/403.jpg",
"rating": "0",
"car_model": "this",
"number_sit": "4",
"distance": 0.035574527536789
}
],
"operator": [],
"nearestdistance": [
{
"distance": 0.03541809,
"time": 5
}
],
"car_models": [
"Taxi"
]
}
]
}
I just want anyone of you to guide me or show me the way. And also please someone tell me what will be the use of "send data" here. What is the use? I promise i will not ask any basic questions after i catch the grip. Help me please.
You can save the parsed data in an array, and for what I can see, there's a lot of tags in the JSON object. I suggest you to create an object of the type "Driver" or "Car", and then save all the data in that object. Once you have the data parsed and saved in an Array of the type of your object (Let's say an array of "Drivers" then you can use the info to add it into the Map.