D.O. February 2016

How to read a Json inside a Json in java?

I'm trying to get the data of this Json. As you can see the first element have a json inside of the json.

{
   "client":{
      "colour":"aabb11",
      "height":200,
      "xpos":0,
      "packages":"com.samsung.incallUi",
      "events":[
         {
            "action":"hide",
            "class":"com.android.TextView",
            "type":"2"
         },
         {
            "colour":"00FF00",
            "action":"show"
         }
      ],
      "width":600,
      "ypos":20
   },
   "Map":" {red=blue, yellow=brown}",
   "Country":"IT"
}

I get the json from:

Request request = new Request.Builder().url(INIT_URL).post(formBody).build();
Response response = client.newCall(request).execute();

I'm trying this, but don't work (give me an JsonSyntaxException):

...
JSONArray ja = new JSONArray(response.body().string());
for (int i = 0; i < ja.length(); i++) {
    JSONObject jo = ja.getJSONObject(i);

    String client = jo.getString("client");
    String xpos = jo.getString("height");
    String packages = jo.getString("xpos");
    String events = jo.getString("packages");
    ...
}
... 

Answers


Pablo Rivero February 2016

The first element, "client" is an object not an array. try

JSONObject ja= new JSONObject(response.body().string());


MiguelCatalan February 2016

I recommend you to take a look into a JSON parser, such us Jackson or Gson.

Will do your life much easier.

//Jackson example
Client client = new ObjectMapper().readValue(jsonString, Client.class);

Just define your Client class with the fields in the JSON


gj_ February 2016

I strongly recommend using Gson. If you can't get it right with gson, that means, your model is not correct. If you have a hard time creating the model for the json, you can auto generate the model instead of creating it your self.

Post Status

Asked in February 2016
Viewed 3,146 times
Voted 14
Answered 3 times

Search




Leave an answer