这是Android的解析JSON数据的最佳方式? [英] Which is the best way to parse JSON data in Android?
问题描述
我JSON数据来分析。该结构不固定,有时它是作为一个单一的字符串等倍的阵列
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.
目前,我们正在使用的GSON库解析JSON,但说到为数组所面临的问题。
Currently, we are using the GSON library for parsing JSON, but are facing problems when it comes as an array.
例如:
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.
谁能帮我?如果我决定使用JSON解析,这将是非常乏味的,因为我有大约20 + API来解析和每个API包含50场的的最小值。
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.
推荐答案
您可以使用的的JSONObject 和 JSONArray 类,而不是GSON一起工作JSON数据
You can use JSONObject and JSONArray classes instead of GSON to work with JSON data
第一个例子
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");
对于第二个示例
String jsonStr = ... // "your JSON data";
JSONObject jsonObj = new JSONObject(jsonStr);
JSONArray jsonArr = jsonObj.getJSONArray("msg");
JSONObject arrItem = jsonArr.getJSONObject(0);
//and so on
另外的JSONObject类有方法OPSTRING,opArray不抛出异常,如果你想了解我是不存在的或有一个错误的数据类型
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
例如
JSONArray arr = jsonObj.optJSONArray("msg");
JSONObject msg = null;
if (arr != null) {
msg = arr.getJSONObject(0)
} else {
msg = jsonObj.getJSONObject("msg");
}
这篇关于这是Android的解析JSON数据的最佳方式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!