[英]how to deserialize a json object to collection using jackson
我想反序列化这样的json
{
"0":{"name":"Alice"},
"1":{"name":"Bob"}
}
到 java 集合(集合或列表,而不是映射)。 我想更改CollectionDeserializer
的默认行为以支持这一点并将其配置为全局配置。 有什么办法吗?
如果你真的有这个结构(一个对象作为一个容器而不是一个数组,它可以更容易处理):
import com.fasterxml.jackson.databind.*;
import java.io.IOException;
import java.util.Iterator;
import java.util.Map;
public class Main {
public static void main(String[] args) throws IOException {
String json = "{\"0\":{\"name\":\"Alice\"}, \"1\":{\"name\":\"Bob\"}}";
ObjectMapper mapper = new ObjectMapper();
JsonNode obj = mapper.readValue(json, JsonNode.class);
Iterator<Map.Entry<String, JsonNode>> userEntries = obj.fields();
while(userEntries.hasNext()){
Map.Entry<String, JsonNode> userEntry = userEntries.next();
System.out.println(userEntry.getKey() + " => " + userEntry.getValue());
}
}
}
您可以使用 gson api 完成此任务。 代码如下:
String yourJson = "{\"0\":{\"name\":\"Alice\"}, \"1\":{\"name\":\"Bob\"}}";
Gson gson = new Gson();
Type tarType = new TypeToken<Map<String,Map<String,String>>>(){
}.getType();
gson.fromJson(yourJson, tarType);
为此,您需要添加以下内容:com.google.gson.Gson
为什么不把你的 JSON 文档变成一个数组:
{"persons":[{"name":"Alice"},{"name":"Bob"}]}
然后定义一个对应的 JSON 模式(假设PersonArray
是文件名):
{
"$schema": "http://json-schema.org/draft-04/schema#",
"description": "Some description",
"type" : "object",
"properties" : {
"persons" : {
"type" : "array",
"items" : { "$ref": "#/definitions/person" }
}
},
"definitions": {
"person" : {
"type": "object",
"description": "A person",
"properties": {
"name": { "type": "string" }
}
}
}
}
并通过使用jsonschema2pojo-maven-plugin
Maven 插件来利用 Jackson Data Binding API 在 Java 中生成 POJO(或者,您可以手动实现 POJO)。
生成 POJO 后,您可以通过以下方式使用 ObjectMapper 反序列化 JSON 文档:
ObjectMapper mapper = new ObjectMapper();
PersonArray personArray = mapper.readValue(serialisedJsonDocument, PersonArray.class);
JSON 文档的元素将存储在PersonArray
对象中:
List<Person> persons = new ArrayList<Person>();
如果需要,您还可以向Person
对象添加其他属性。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.