我正在尝试将此 json 反序列化为 POJO 类,这样我就能够管理这些对象。 JSON:
{
"something": "x",
"items": [
{
"type": "y",
"id": "123",
"otherInfo": {
"tag": "abc",
"otherId": [
{
"first": "qaz",
"second": "zaq"
},
{
[...]
像这样的元素有10多个。 我想反序列化它,所以我使用了 jsonschema2pojo,使用 getter、setter 和构造函数创建了像 Item 和 otherInfo 这样的类。
然后我在 DAO 类中创建了一个 ObjectMapper:
ObjectMapper mapper = new ObjectMapper();
Item items;
{
try {
items = mapper.readValue(new File("path/file.json"), Item.class);
} catch (IOException e) {
e.printStackTrace();
}
}
public Item getAllItems(){
return items;
}
这样我会得到一个空的输出。 将 Item 更改为 Item[] 时,我收到“MismatchedInputException”,因为 JSON 中的“items”上方有“某物”。
当我尝试引用比 Item 高一级的 POJO 类时,我将整个 JSON 作为单个数组元素,其中包含所有内容。很明显,但这表明 ObjectMapper 工作正常。
是否有任何简单或有效的方法可以像这样反序列化 JSON?
最佳答案
您可以创建一个包含 ArrayList 的父对象来表示 Item 数组。
例如:
public class MyParentObject {
String something;
ArrayList<Item> items;
public ArrayList<Item> getItems() {
return items;
}
// the rest of your getters/setters
}
// the object mapper line becomes:
MyParentObject parentObject = mapper.readValue(new File("path/file.json"), MyParentObject.class);
ArrayList<Item> items = parentObject.getItems();
通过JSON反序列化,可以将JSON数组直接映射到ArrayList。
关于java - 将复杂的 json 文件反序列化为 POJO - 要么作为一个列表元素工作,要么不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55435650/