ThemuRR
ThemuRR

Reputation: 61

How do I parse this JSON in Java?

I'm a bit new to this and it's doing my head in! I keep getting this error:

Error parsing data org.json.JSONException: No value for tname

This is the json:

[{"tname":"2"},{"kword":"||ice+skating+rink"}]

And here is my java code:

String result = response.toString();

            try
            {
                JSONArray jArray = new JSONArray(result);

                for (int i = 0; i < jArray.length(); i++) {
                    JSONObject json_data = jArray.getJSONObject(i);
                    Log.i("log_tag", ", type: " + json_data.getString("tname")+
                            ", keyword: " + json_data.getString("kword"));

                    type += json_data.getString("tname");
                    keyword += json_data.getString("kword");
                }

Any help greatly appreciated.

Upvotes: 1

Views: 104

Answers (1)

l-l
l-l

Reputation: 3854

Your second object doesn't have tname. you should check and see if the object has a property before accessing it

if(json_data.has("tname"))    
    type += json_data.getString("tname");
if(json_data.has("kword"))           
    keyword += json_data.getString("kword");

Upvotes: 5

Related Questions