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.
Related
I am really new to JSON Parsing and learning everyday.
I have a specific JSON response I have to parse but I am finding no luck doing it.
I am using Volley for Parsing Request.
Here is my response:
{
"error": false,
"message": "Favourties fetched successfully",
"code": 200,
"data": [
{
"id": "5f1980f8c42e1f60854c57e4",
"type": 1,
"status": 1,
"favourite": {
"_id": "5f118057f44ebd1cead089db",
"firstName": "Bilal",
"lastName": "Khan",
"businessName": "Master Paint",
"image": "https://welist-assets.s3.us-west-2.amazonaws.com/profile_images/1592383845941-default_avatar.png"
},
"createdAt": "2020-07-23T12:22:16.731Z",
"updatedAt": "2020-07-23T12:22:16.731Z"
},
{
"id": "5f198084c42e1f60854c57e2",
"type": 3,
"status": 1,
"favourite": {
"images": [],
"_id": "5f12d5345478a53584eca98b",
"name": "Water Paint7"
},
"createdAt": "2020-07-23T12:20:20.680Z",
"updatedAt": "2020-07-23T12:20:20.680Z"
}
]
}
I am able to get the Array which contains 2 object, but I am unable to get the data inside the nested favorites.
try {
Log.d("Onresponse", response);
//converting the string to json array object
JSONObject obj = new JSONObject(response);
JSONArray array = obj.getJSONArray("data");
//traversing through all the object
for (int i = 0; i < array.length(); i++) {
//getting product object from json array
JSONObject favorites = array.getJSONObject(i);
Log.d("lenght", favorites.getString("status"));
//adding the product to product list
favoriteList.add(new FavoriteVendorsModel(
favorites.getString("firstName"),
favorites.getString("lastName"),
favorites.getString("businessName"),
favorites.getString("image")
));
}
Here is my method.
You have skipped one level of nesting. By calling array.getJSONObject(i) you get:
{
"id": "5f1980f8c42e1f60854c57e4",
"type": 1,
"status": 1,
"favourite": {
"_id": "5f118057f44ebd1cead089db",
"firstName": "Bilal",
"lastName": "Khan",
"businessName": "Master Paint",
"image": "https://welist-assets.s3.us-west-2.amazonaws.com/profile_images/1592383845941-default_avatar.png"
},
"createdAt": "2020-07-23T12:22:16.731Z",
"updatedAt": "2020-07-23T12:22:16.731Z"
}
And you are trying to call directly on that object next getString methods:
favorites.getString("firstName");
favorites.getString("lastName");
favorites.getString("businessName");
favorites.getString("image");
When actually you must first get JSONObject named favourite and then call these getString method on it:
JSONObject favorite = favorites.getJSONObject("favourite");
favorite.getString("firstName");
favorite.getString("lastName");
favorite.getString("businessName");
favorite.getString("image");
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"
}
]
}
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
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.
I am trying to parse data from a MongoDB cloud server. My JSON data returned from the server is as follows:
[
{
"_id": {
"$oid": "4e78eb48737d445c00c8826b"
},
"message": "cmon",
"type": 1,
"loc": {
"longitude": -75.65530921666667,
"latitude": 41.407904566666666
},
"title": "test"
},
{
"_id": {
"$oid": "4e7923cb737d445c00c88289"
},
"message": "yo",
"type": 4,
"loc": {
"longitude": -75.65541383333333,
"latitude": 41.407908883333334
},
"title": "wtf"
},
{
"_id": {
"$oid": "4e79474f737d445c00c882b2"
},
"message": "hxnxjx",
"type": 4,
"loc": {
"longitude": -75.65555572509766,
"latitude": 41.41263961791992
},
"title": "test cell"
}
]
The problem I am having is the data structure returned does not include a name of the array of JSON objects. Each object returned is a "post". But how do I parse it using GSON if the there is no name for the array of JSON objects. I would like to put these "posts" into an ArrayList of type Post.
Piece of code you are looking for:
String jsonResponse = "bla bla bla";
Type listType = new TypeToken<List<Post>>(){}.getType();
List<Post> posts = (List<Post>) gson.fromJson(jsonResponse, listType);
Use the contructor for JSONArray to parse the string:
//optionally use the com.google.gson.Gson package
Gson gson = new Gson();
ArrayList<Post> yourList = new ArrayList<Post>();
String jsonString = "your string";
JSONArray jsonArray = new JSONArray(jsonString);
for (int i = 0; i < jsonArray.length(); i++){
Post post = new Post();
//manually parse for all 5 fields, here's an example for message
post.setMessage(jsonArray.get(i).getString("message"));
//OR using gson...something like this should work
//post = gson.fromJson(jsonArray.get(i),Post.class);
yourList.Add(post);
}
Considering there are only 5 fields, using Gson might be more overhead than you need.