How to remove extra json object in flutter - android

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"
}
]
}

Related

JSON data - How to parse?

Suppose I have data in JSON. How can I parse the data so I can get the values of nested objects (e.g. kind, id and title)?
My JSON data is:
{
"kind": "youtube#playlistItemListResponse",
"items": [
{
"id": "UExkc1JWcGJNV19LSH",
"items":[
{
"title": "New Updates",
}
],
}],
}
Well you should remove all the commas since last items should not be followed by one.
So more like:
{
"kind": "youtube#playlistItemListResponse",
"items": [{
"id": "UExkc1JWcGJNV19LSH",
"items": [{
"title": "New Updates"
}]
}]
}
Other than that you can just use JSONObject lib and extract the value you need. For example to get the kind:
JSONObject jsonObj = new JSONObject(strInput);
String kind = jsonObj.getString("kind"); // kind now contains "youtube#playlistItemListResponse"
where strInput is the above json as a string.
More info: https://developer.android.com/reference/org/json/JSONObject

Nested JSON parsing in android using url

I am new to JSON parsing and I am stuck in this nested JSON parsing.Here is the attached JSON data for one city only which I get from the url :
{
"CityCode": 142,
"CityName": "Yavatmal",
"State": {
"StateCode": 21,
"StateName": "Maharashtra",
"CountryCode": 1,
"Country": {
"CountryCode": 1,
"CountryName": "India",
"IsdCode": "+91"
}
},
"Country": {
"CountryCode": 1,
"CountryName": "India",
"IsdCode": "+91"
},
"GPlaceId": "ChIJ3U60i8zo0zsR4L7sQeqtd0g",
"Latitude": 20.388794,
"Longitude": 78.120407,
"ActiveStatus": 1
}
Can anyone tell me how to parse this type of JSON data in such a way that I can display each key in a textView.
the scope sorrounded by "{" "}" are called json object. You can extract like `
String jsonData = ""//received json string
jsonObject obj = new JSONSObject(jsonData);`
obj.getString("CityCode");
obj.getJSONObject("state");
if the key hold the single value , then you can get that in string. If the key itself hold another jsonobject , extract that into separate jsonobject and repeat.

How to handle missing key in JSON when using Retrofit Library to fetch data android

I'm using efficient retrofit library to get data. The json i am getting through api is as given below:
[
{
"doctor_detail": [
{
"experience_years": null,
"clinic": [
{
"price": 163,
"main_facility": {
"name": "West Delhi Dental Clinic",
"address": {
"mobile": "+911166107201",
"latitude": null,
"longitude": null,
"locality": {
"city": {
"name": "Delhi"
},
"name": "Janak Puri"
}
}
}
}
],
"specialities": [
{
"name": "Dentist",
"slug": "dentist"
}
],
"owner": {
"first_name": "Bhudev",
"last_name": "Sharma",
"middle_name": null
},
"logo": [],
"doctor_id": "286207",
"education": []
},
{
"experience_years": null,
"clinic": [],
"specialities": [],
"owner": {
"first_name": "Hema",
"last_name": "Anand",
"middle_name": null
},
"logo": [],
"doctor_id": "12137",
"education": []
}
]
},
{
"last_page": 2
},
{
"title": "dentist"
}]
In First object of json i am getting an array with key doctor_detail having two bjects in first object i am getting an array with key clinic having price key and an array main_facility having some other keys like name,address.
but in second object of doctor_detail i am getting same clinic key but don't having any key inside clinic due to this i am getting a run time error :
java.lang.IndexOutOfBoundsException: Invalid index 1, size is 1
at java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java:255)
in RecyclerAdapter when i am going to get price for second object from ArrayList<String> mPriceArrayList.
So please tell me if there is any way to handle such kind of problem.
Thanks
Dear Ravi i think its not your problem you are getting wrong JSON but still
you can handle it by using try-catch block in adapter where you are getting ArrayIndexOutOfBounds Exception and you can set any value in text view in catch block for which you are not getting keys like:
try{
mPriceTextView.setText(mPriceArrayList.get(getAdapterPosition()));
}catch(Exception oe){
mPriceTextView.setText("price is missing");
}
Finally i got answer this is due to wrong json. It can not be handle.

Deserializing different objects in JSON array (GSON)

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)

How to parse this JSON file to some ArrayList<String>?

in the past i have already parsed a json file from url to local sqlite database and the json source was like the following one:
[
{
"origin": "accommodation",
"parent": "",
"en": "Accommodation"
},
{
"origine": "book",
"parent": "shopping",
"en": "Book"
},
{
"origin": "university",
"parent": "education",
"en": "University"
}
]
But now it seems to be different. I validate the following json file so i'm sure it is a valid json, but it is formatted in a different way, so i do not know how to parse it in the right way. In addition this time i would put the content in an ArrayList. Here is the json file:
{
"city1": {
"item1": {
"score": 6196.58,
"step": 0.00423,
"name": "User 1",
"form": "yellow"
},
"item2": {
"score": 106.86,
"step": 2.5822,
"name": "User 2",
"form": "yellow"
},
"item3": {
"score": 671.48,
"step": 0.387,
"name": "User 3",
"form": "yellow"
},
},
"misc": {
"online_users": {
"kind1": 18,
"kind2": 3
},
"ops": [
""
]
},
"city2": {
"item1": {
"score": 6196.58,
"step": 0.00405,
"name": "User 1",
"form": "yellow"
},
"item2": {
"score": 179563.93,
"step": 0.000138,
"name": "User 2",
"form": "yellow"
},
"min_size": {
"line": 10
},
"out_of_sync": [
"0e888069530497506433b5f0cacb",
"b428fa3a9b9e13cf8b26196bfcc7",
"f42442a2e46523f059809f83f1a9"
],
},
}
Can you tell me how to handle these values and how to put in some arraylist?
There are several ways to do this, but I'll post the way I feel like makes the most sense. If you don't mind putting this in separate arrays you can do this:
String stringOfJSONCode = <read in the JSON here>;
JSONObject json = new JSONObject(stringOfJSONCode);
Iterator<String> iter = json.keys();
while (iter.hasNext()) {
String key = iter.next();
try {
Object value = json.get(key);
} catch (Exception e) {
}
}
You need to use an iterator to loop through a JSONObject. You could use any other loop to loop through JSONArrays. This will iterate through the outer objects, like city1, misc, city2. The key will be either city1, misc, or city2.
If you want to get those, just add this within the 'try'
JSONObject object = json.getJSONObject(key);
or
JSONArray array = json.getJSONArray(key);
depending on what you're trying to get. Once you have these, you can do the following:
JSONObject city1 = object.getJSONObject("item1");
List<String> jsonList = new ArrayList<String>();
jsonList.add(object.getDouble("score"));
jsonList.add(object.getDouble("step"));
jsonList.add(object.getString("name"));
jsonList.add(object.getString("form"));
If you are not sure if it will be item1 or whatever, you can iterate through it again using the iterator and add each item in dynamically. Also you can make another try-catch, try to get a JSONArray, if it is not an array it will go in the catch, and then iterate through the object.
You could also make a hashmap or 2D array to add everything in the same array.
Hope this helps
Why don't you let jackson mapper do it's magic?
The only thing you'll need then would be appropriate DTO classes.

Categories

Resources