I have already checked other posts of Stack Overflow regarding Json data parsing but did not find the solution to parse inner Json int objects.
I am getting the following response from a web service.
{
"counter":[
{
"1":[
{
"message":"28",
"events":0,
"shared_files":"8"
}
],
"2":[
{
"message":"39",
"events":"4",
"shared_files":"7"
}
]
.....
"n":[
{
"message":"39",
"events":"4",
"shared_files":"7"
}
]
}
]
}
Where "1", "2" and "n" are ids and json object size changes according to the data. I am able to parse the above response till JsonObect using following code:
JsonArray jsonArray = GetJson_.getArray(response, "counter");
if (jsonArray != null) {
JsonObject object = jsonArray.get(0).getAsJsonObject();
}
and my jsonObject now looks like
{
"1":[
{
"message":"28",
"events":0,
"shared_files":"8"
}
],
"2":[
{
"message":"39",
"events":"4",
"shared_files":"7"
}
]
.....
"n":[
{
"message":"39",
"events":"4",
"shared_files":"7"
}
]
}
But I am stuck at how to parse the JsonObject which is dynamic.
Please help.Thanks in advance.
hey you may use HashMap<> for parse dynamic key response for this check this link, other way you may use Iterator which i done below :
JSONObject jsonObject= m_jArry.getJSONObject(0);
Log.e("ad","--------"+jsonObject.toString());
Iterator keys = jsonObject.keys();
while(keys.hasNext()) {
// loop to get the dynamic key
String currentDynamicKey = (String)keys.next();
// get the value of the dynamic key
JSONObject currentDynamicValue = jsonObject.getJSONObject(currentDynamicKey);
// do something here with the value...
}
Hope this will helpful to you.
Related
I need to parse a json with the structure as follows:
{
"names": {
"nameOne": {
"item": "my item"
},
"nameOther": {
"item": "my item 2"
},
... more elements with no prevously known attribute name
}
}
How could i retrieve it if i do not know how many nameOne, nameOther...nameX exist? My problem is to model that json, so i can not use a SerializedName. I think maybe exists something like a hashmap to store that objects.
use like this
#Expose
#SerializedName("names")
private HashMap<String, String> map;
map key will contains 'nameOne,.......'
use Gson as json parsing
This is not valid JSON structure. Anyway you can check this
How to parse JSON Array (Not Json Object) in Android
for parsing a JSON list it is not important how many elements will be in list. Do the simple for loop through the list elements and voila. Or even better use create something like this to parse a response :
public class Foo {
private List<Names> objects;
}
and you can use serializable here
you can loop through jsonObject's keys and add them to a map
Object obj = new JSONParser().parse(new FileReader("JSONExample.json"));
JSONObject jo = (JSONObject) obj;
Iterator<String> keys = jo.keys();
while(keys.hasNext()) {
String key = keys.next();
if (jo.get(key) instanceof JSONObject) {
// do something with jsonObject here
}
}
So I have a json response from web service like this
{
error: false
types: [2]
-0: {
card_type_id: 5
category: "Food & Beverages"
}
-1: {
card_type_id: 8
category: "Entertaiment"
}
}
what I want to do is to get the number inside json array "types" and use it to looping to set the value of arraylist that will be use in listview, but my code seems and cannot get the json array length, this is my code
JSONObject obj = new JSONObject(response);
if(!obj.getBoolean("error")){
JSONArray types = obj.getJSONArray("types");
for(int i=0; i<types.length();i++)
{
JSONObject a = types.getJSONObject(i);
int ct_id = a.getInt("card_type_id");
String category = a.getString("category");
CardType ct = new CardType();
ct.setTypeId(_ct_id);
ct.setTypeCategory(_category);
categoryArray.add(ct);
}
}
Can anyone help me? Thanks before
This is what your JSON response probably should look like (note also that keys and string values should be sorrounded by double-quotes):
{
"error": false,
"types": [
{
"card_type_id": 5,
"category": "Food & Beverages"
},
{
"card_type_id": 8,
"category": "Entertaiment"
}
]
}
The JSONArray "types" in this example has a length (types.length()) of 2. Now you can implement your for-loop and should get the expected results.
actually it's just my fault to see the json from advanced rest client, i use the json menu and the app automatically correct the json and become invalid, after i change to raw menu i can see the actual json and correct the code
i have a JSON like below.
this is sample json.. i have my json structure like this. if this json has any error please ignore that.
[
[
"{"category_id":1,"category_name":"1Appetizers","image_id":0}",
"{"category_id":13,"category_name":"Buffet","image_id":0}"
],
[
"{"subcategory_id":1,"category_id":12,"subcategory_name":"Beer","image_id":0}",
"{"subcategory_id":2,"category_id":12,"subcategory_name":"Wine","image_id":0}"
],
[
"{"menucategory_id":1,"menucategory_id":12,"menucategory_name":"dosa","image_id":0}",
"{"menucategory_id":2,"menucategory_id":12,"menucategory_name":"idly","image_id":0}"
]
]
how do i parse this JSON in android. i want to show category_name in one page and other details in some other page. there is no name for object.
Like the other commenters have mentioned this is not real JSON.
But here is an attempt to answer your question anyway.
I would create objects that represents the data you want to serialize and deserialize to and form JSON. It looks like you would have objects Category, Subcategory, and MenuCategory. Then you would probably have another object that holds lists of those three objects.
Then I would use GSON to serialize and deserialize your object. Let it do the heavy lifting for you.
try the following code. it might help you
// say you have your json in a String named jsonString
try
{
JSONArray array = new JSONArray(jsonString);
JSONArray firstJsonArray = array.getJSONArray(0);
JSONArray secondJsonArray = array.getJSONArray(1);
JSONArray thirdJsonArray = array.getJSONArray(2);
for (int i = 0; i < 2; i++)
{
JSONObject firstJsonObject = firstJsonArray.getJSONObject(i);
JSONObject secondJsonObject = secondJsonArray.getJSONObject(i);
JSONObject thirdJsonObject = thirdJsonArray.getJSONObject(i);
String categoryName = firstJsonObject.getString("category_name");
String subcategoryName = secondJsonObject.getString("subcategory_name");
String menucategoryName = thirdJsonObject.getString("menucategory_name");
// Now here you can use these values to do anything
}
}
catch (JSONException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
I'm currently working on an Android application that gets a JSON response from a website called CloudMine. Their responses are typically in this format:
{
"success": {
"key1": { "field": "value1" },
"key2": { "field1": "value1", "field2": "value2" }
},
"errors": {
"key3": { "code": 404, "message": "Not Found" }
}
}
I currently want to loop through all the objects in the "success" object so I can access the different fields in each object. However, I've only been taught how to use the JsonParser from the gson API. The closest I got was using the names() method on the success object but Eclipse yelled at me because the method is undefined for this type.
I appreciate all the help that anyone can give me.
Thanks!
This worked for me:
JsonObject myJsonObject = new Gson().fromJson(myJsonString, JsonObject.class);
for (Map.Entry<String, JsonElement> entry : myJsonObject.entrySet()) {
JsonObject entryObj = entry.getValue().getAsJsonObject();
}
Based on the accepted answer to this question, although I've altered it for my use case:
Iterate over JsonObject properties
Here's a very simple code that would iterate over objects in 'success':
JSONObject json = new JSONObject(responseString);
JSONObject success = json.getJSONObject("success");
JSONObject one;
for(Iterator it=success.keys(); it.hasNext(); ) {
one = success.getJSONObject((String)it.next());
//deal with the next object inside your 'success'
}
On a web service I a, getting a json as follows in android application. I would likes to make a loop table view in android with lists object. Please help me how to make the loop. I successed by making table row. Still I am confusing with how to pass data
My JSON
{
"id":4,
"access_token":"tge4sn1vdgbjcvvf",
"session":1,
"lists":[
{
"name":"name 1"
},
{
"name":"name 2"
},
{
"name":"name 3"
},
{
"name":"name 4"
},
{
"name":"name 4"
}
]
}
My Code
if (response != null) {
InputStream in = response.getEntity().getContent();
String a = convertStreamToString(in);
JSONObject jsono = stringToJsonobj(a);
String passedStringValue = jsono.getString("session");
if(passedStringValue.equals("1")){
// I want the loop here
// Tried this - myListsAll=jsono.getJSONObject("lists");
}
Any one please help me how to parse this data
Thanks in advance
lists is JSONArray instead of JSONObject.currently you are trying to get it as an JSONObject.you can iterate through lists JSONArray as:
if(passedStringValue.equals("1")){
JSONArray myListsAll=jsono.getJSONArray("lists");
for(int i=0;i<myListsAll.length();i++){
JSONObject jsonobject=myListsAll.getJSONObject(i);
// get name from jsonobject object
String str_name=jsonobject.optString("name");
}
}