我一直在使用股票org.json库并熟悉这一点。我现在想要出于性能原因使用Jackson库,但我正在努力适应看起来非常不同的框架。采用以下JSON:
{"result":[[{"usUserName":"FRED","usActive":true},{"usUserName":"JIM","usActive":true},{"usUserName":"DAVID","usActive":true}]]}
使用org.json我解析如下:
try {
JSONArray jsonRecordset = response.getJSONArray("result").getJSONArray(0);
JSONObject jsonFirstRecord = jsonRecordset.getJSONObject(0);
Log.i("myloginfo", jsonFirstRecord.getString("usUserName"));
} catch (JSONException e) {
e.printStackTrace();
}
我想和杰克逊一起复制,但看不出去哪里,因为它看起来非常不同。我的JSON来自一个我无法控制的Web服务。上面的数据仅用于说明,我的实际数据要大得多,因此我希望获得最佳性能。
答案 0 :(得分:1)
通常的方法是,不是手动切片和切块,而是定义一个与JSON结构兼容的Java类(或多个类)。像这样:
public class Response {
public UserInfo[][] result;
}
public class UserInfo {
public String usUserName;
public boolean usActive;
}
ObjectMapper mapper = new ObjectMapper(); // must reuse for good performance
Response resp = mapper.readValue(jsonInput, Response.class);
// and use 'resp' however you want, now has the expected data.
也可能像杰森那样使用杰克逊,所谓的树模型;为此你可以查看教程。当数据没有良好的对象结构时(即设计为不能从OO语言轻松访问),或者如果您只需要大型文档中的小片段,它的效果会更好。