Mdlc
Mdlc

Reputation: 7288

Parse simple JSON Array

I'm trying to parse this relatively simple JSON array:

{
   "tags":[
      "Cheese",
      "Milk",
      "Yoghurt"
   ],
   "success":1,
   "message":"Tags found"
}

What I've got is this:

        Log.d("Tag products: ", json.toString());

        try {
            // Checking for SUCCESS TAG
            int success = json.getInt("success");

            if (success == 1) {
                // products found
                // Getting Array of Products
                JSONArray products = json.getJSONArray("tags");

            } else {
                // no products found
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

My Array is logged to my logcat perfectly. I'm succesfully retrieving the value of success and message. But I can't parse the actual tags.

Most examples and tutorails about json parsering use another format than I do, so I also would be more than happy with an example that demonstrates the parsing of this kind of array.

Upvotes: 0

Views: 178

Answers (2)

Raghunandan
Raghunandan

Reputation: 133560

Loop through the json array and get the items based on index.

To parse

JSONArray products = json.getJSONArray("tags");
for(int i=0;i<products.length();i++)
{
String value= (String) products.get(i);
Log.i(".........",value);
}

You can also look @ gson

https://code.google.com/p/google-gson/

Upvotes: 1

Mobility
Mobility

Reputation: 263

The json object you have shared can be modelled to the following Model class:

 public class ModelClass
    {
        public List<string> tags { get; set; }
        public int success { get; set; }
        public string message { get; set; }
    }

Once you have parsed the json string to an object of ModelClass then you can access the list of tags and get the values in it.

You can use the gson parser to do the deserialization.

Gson gsonParser = new Gson();
ModelClass modelObject = new ModelClass();
modelObject = gsonParser.fromJson(jsonString, modelObject.getClass());

for(String tagString : modelObject.tags)
{
   Log.d("AppTag", tagString);
}

Upvotes: 0

Related Questions