简体   繁体   English

在Java中列出的情况下,杰克逊JSON反序列化错误

[英]Deserialize error with jackson json in case of list in java

I have create a JSON with Jackson based on this class: 我已经基于此类使用Jackson来创建JSON:

    public class One {
    public long param;

    public List<Two> two;

    public static class Two{
        public long param;
        public List<Short> param2;
    }
}

I have defined two constructor for each class and I use it for the creation of the objects that later are written on the json file. 我为每个类定义了两个构造函数,并用它来创建对象,这些对象随后将写入到json文件中。 The outcome is (valid JSON): 结果为(有效JSON):

[{"param":1,"Two":[{"param":4,"param2":[1,2,3]},{"param":5,"parma2":[4,5,6]}]},{"param":2,"Two":[{"param":6,"param2":[1,2,3]}]}]

Now I would like to read and load the parameters and I define: 现在,我想读取并加载参数并定义:

    mapper.configure(Feature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true); //tried with and without
    JsonFactory f = new JsonFactory();
    JsonParser jp;
jp = f.createJsonParser(FILE);
    jp.nextToken();
    while (jp.nextToken() == JsonToken.START_OBJECT) {
         mapper.readValue(jp, One.class);
     }
     jp.close();

I have this error: 我有这个错误:

Can not deserialize instance of json.One$Two out of START_ARRAY

I have found the solution. 我找到了解决方案。

Load of the json file: 加载json文件:

List<One> myObjects = new ArrayList<One>();
myObjects = mapper.readValue(FILE, mapper.getTypeFactory().constructCollectionType(List.class, One.class));

The code in the class is edited by adding only @JsonProperty("Two") : 通过仅添加@JsonProperty("Two")来编辑类中的代码:

   public class One {
    public long param;
    @JsonProperty("Two")
    public List<Two> two;

    public static class Two{
        public long param;
        public List<Short> param2;
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM