Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which is the best way to parse JSON data in Android?

I have JSON data to parse. The structure is not fixed, and sometimes it comes as a single string and other times as an array.

Currently, we are using the GSON library for parsing JSON, but are facing problems when it comes as an array.

For example:

1.  {"msg":"data","c":300,"stat":"k"}


2. {
    "msg": [
        " {\"id\":2,\"to\":\"83662\",\"from\":\"199878\",\"msg\":\"llll\",\"c\":200,\"ts\":1394536776}"
     ],
     "c": 200,
     "stat": "k",
     "_ts": 1394536776
 }

In the example above, sometimes I get msg as a string and sometimes as an array.

Can anyone help me? If I decide to use JSON parsing, it will be very tedious because I have around 20+ API to parse and each API contains a mininum of 50 fields.

like image 550
user3064556 Avatar asked Mar 11 '14 12:03

user3064556


1 Answers

You can use JSONObject and JSONArray classes instead of GSON to work with JSON data

for the first example

String jsonStr = "{\"msg\":\"data\",\"c\":300,\"stat\":\"k\"}";

JSONObject jsonObj = new JSONObject(jsonStr);

String msg = jsonObj.getString("msg");
Integer c = jsonObj.getInteger("c");
String stat = jsonObj.getString("stat");

For the second example

   String jsonStr = ... // "your JSON data";

   JSONObject jsonObj = new JSONObject(jsonStr);

   JSONArray jsonArr = jsonObj.getJSONArray("msg");

   JSONObject arrItem = jsonArr.getJSONObject(0);

   //and so on

Also JSONObject class have method opString, opArray which does not throw exception if data you trying to get is not exist or have a wrong type

For example

JSONArray arr = jsonObj.optJSONArray("msg");
JSONObject msg = null;
if (arr != null) {
    msg = arr.getJSONObject(0)
} else {
   msg = jsonObj.getJSONObject("msg");
}
like image 172
Sergey Pekar Avatar answered Sep 22 '22 02:09

Sergey Pekar