[英]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.