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.
You can use JSONObject and JSONArray classes instead of GSON to work with JSON data
for the first example
For the second example
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
You can use Google GSON lib for directly parse the json to class object. This is easy and accurate.Okay do one thing both time code is different, if the code is 300 directly parse the json object without GSON. if the code is 200 the use the GSON (Define the similar java class)
There are two ways to parce JSON.
Refer the code snippet below to deserialize your json using Google's Gson library without exceptions.
MyMessage class