我有以下JSON,我想使用Jackson JSON Processor库(http://jackson.codehaus.org/)解析它:
{
"wrapper":{
"general":{
"value":10
},
"items":{
"DOG":{
"0":78,
"1":125
"name":"Lucky",
"features":{
"color":"brown",
"sex":"male"
}
},
"CAT":{
"0":123,
"1":94
"name":"Fluffy",
"features":{
"color":"black",
"sex":"female"
}
},
"MOUSE":{
"0":23,
"1":33
"name":"Jerry",
"features":{
"color":"gray",
"sex":"male"
}
}
}
}
}
您如何建议成为最佳做法的最佳方式?
答案 0 :(得分:1)
解析JSON的简单快速形式是创建带注释的bean,然后调用Jackson。
有些人喜欢这样:
@JsonIgnoreProperties(ignoreUnknown = true)
public class YourClass {
@JsonProperty("wrapper")
public Wrapper wrapper;
@JsonIgnoreProperties(ignoreUnknown = true)
public static class Wrapper{
@JsonProperty("Items")
public ArrayList<Item> items = new ArrayList<Item>();
}
@JsonIgnoreProperties(ignoreUnknown = true)
public static class Item{
@JsonProperty("name")
public String name;
...
}
....
}
然后在你的Activity / Thread / AsyncTask中:
public ObjectMapper mMapper;
...
if (mMapper == null)
mMapper = new ObjectMapper();
YourClass yourClass = (YourClass) mMapper.readValue(stringJSON, YourClas.class);
重用ObjectMapper非常重要因为它非常昂贵
改进:如果你设置了这个JSON可以改进(bean是基于它的)
{
"wrapper":{
"general":{
"value":10
},
"items":[
"item":{
"name":"DOG",
"0":78,
"1":125
"name":"Lucky",
"features":{
"color":"brown",
"sex":"male"
}
},
"item":{
"name":"CAT",
"0":123,
"1":94
"name":"Fluffy",
"features":{
"color":"black",
"sex":"female"
}
}
]
}