gpt4 book ai didi

java - Jackson 包装器反序列化最佳实践

转载 作者:行者123 更新时间:2023-12-01 13:50:48 28 4
gpt4 key购买 nike

我有以下 JSON,我想使用 Jackson JSON 处理器库 ( 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"
}
}
}
}
}

您如何建议成为最佳实践方面的最佳方式?

最佳答案

解析 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"
}
}
]
}

关于java - Jackson 包装器反序列化最佳实践,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19973762/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com