[英]Deserialize JSON Array with different POJOs in java with Jackson
How can I deserialize this JSON structure ? 如何反序列化此JSON结构?
[
{
"page": 1,
"per_page": "50"
},
[
{
"id": "IC.BUS.EASE.XQ",
"name": "ion"
},
{
"id": "OIUPOIUPOIU",
"name": "lal alalalal"
}
]
]
( I get this back from the WorldBank Api, it is a bit simplified, the exact response you find here ). (我是从WorldBank Api那里得到的,这有点简化了,您可以在此处找到确切的响应)。
The problem is, that i get an array of objects, where the first element is a POJO and the second element is an array of POJOs of a specific type. 问题是,我得到了一个对象数组,其中第一个元素是POJO,第二个元素是特定类型的POJO数组。
The only way that I found out to deserialize this is to be very generic which results in Lists and Maps. 我发现反序列化的唯一方法是非常通用,从而生成列表和地图。
List<Object> indicators = mapper.readValue(jsonString, new TypeReference<List<Object>>() {});
Is there a better way to deserialize this JSON to get an Array or a List, where the first element is of the Object "A" and the second a List of Objects "B" ? 有没有更好的方法反序列化此JSON以获取数组或列表,其中第一个元素是对象“ A”,第二个元素是对象列表“ B”?
If I were you, I would do something like this. 如果我是你,我会做这样的事情。 It's not possible to represent your data in a good way in one list on java without using a common base class.
如果不使用公共基类,就不可能在Java的一个列表中以良好的方式表示数据。 In your case this unfortunately is
Object
. 在您的情况下,不幸的是
Object
。 You can help a bit by manipulating the response list though. 您可以通过处理响应列表来有所帮助。
ArrayNode arrayNode = (ArrayNode) mapper.readTree(this.getScrape().getScrapetext());
A a = mapper.readValue(arrayNode.get(0), A.class);
arrayNode.remove(0);
List<B> b = mapper.readValue(arrayNode.toString(), new TypeReference<List<B>>()
{
});
Given that the structure is rather irregular, in that there is no Java class definition that structurally matches a JSON Array with magic type definitions for elements by index, you probably need to do 2-pass binding. 鉴于结构相当不规则,因为没有Java类定义在结构上将JSON数组与具有按索引的元素的魔术类型定义相匹配的Java定义,您可能需要进行两遍绑定。
First, you bind JSON into either List
(or just Object
) or JsonNode
. 首先,您将JSON绑定到
List
(或只是Object
)或JsonNode
。 And from that, you can use ObjectMapper.convertValue()
to extract and convert elements into actual types you want. 然后,您可以使用
ObjectMapper.convertValue()
提取元素并将其转换为所需的实际类型。 Something like: 就像是:
JsonNode root = mapper.readTree(jsonSource);
HeaderInfo header = mapper.convertValue(jsonSource.get(0),
HeaderInfo.class);
IdNamePair[] stuff = mapper.convertValue(jsonSource.get(1),
IdNamePair[].class);
would let you get typed values from original JSON Array. 可以让您从原始JSON数组获取类型化的值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.