简体   繁体   English

无法使用杰克逊反序列化和序列化Java List <>

[英]Unable to deserializer and serialize Java List<> with jackson

I am trying to deserializer and then serialize a java object. 我正在尝试反序列化,然后序列化一个Java对象。 I got an object like this one- 我有一个像这样的物体

public class Blas{
private Integer blasRootId;

private List<Bla> blaList = new ArrayList<>();

public Blas() {}

/region g & s
getter and setters ..
//endregion
}

And the object - 和对象-

public class Bla{
private String fileName;
private String description;
private Integer id;

public Bla() {}

//region g & s
getter and setters ..
//endregion
}

I deserialize the object with 我反序列化对象

ObjectMapper mapper = new ObjectMapper();
mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);

String jsonString = mapper.writeValueAsString(Blas);

And the created json is like 和创建的json就像

{
"Blas": {
    "blasRootId": 2840,
    "blaList": [
      "java.util.ArrayList",
      [
        {
          "fileName": "RegularPayload",
          "description": "",
          "id": 2260
        }
      ]
    ]
  }
}

So when I try to serialize the created json the following error accord - 因此,当我尝试序列化创建的json时,出现以下错误-

Can not instantiate value of type [simple type, class Bla] from String value        ('java.util.ArrayList'); no single-String constructor/factory method

Who can i make the deserializer to write the list as it is ,without the addition "java.util.ArrayList" list, or how can i read it right? 谁可以使反序列化器按原样写入列表,而无需添加“ java.util.ArrayList”列表,或者如何正确读取?

Update : It was my mistake, I added in the "mapper.configure" a parameter (That i don't recall which) that caused the serializer to add the "java.util.ArrayList". 更新:这是我的错误,我在“ mapper.configure”中添加了一个参数(我不记得是哪个参数),该参数导致序列化程序添加了“ java.util.ArrayList”。 My code example should work fine. 我的代码示例应该可以正常工作。

As prsmax asked, it depends how the code were you try to deserialize blas looks like, it seems like you are trying to take the string of blas and deserialize like this: 正如prsmax所问,这取决于您尝试对blas进行反序列化的代码的样子,似乎您正在尝试采用blas字符串并进行反序列化,如下所示:

mapper.readValue(blasStr, Bla.class)

If you want only to deserialize a list of Bla you can do this: 如果只想反序列化Bla列表,则可以执行以下操作:

    JavaType javaType = mapper.getTypeFactory().constructCollectionType(ArrayList.class, ValueType.class);
    List<ValueType> list = mapper.readValue(str, javaType);

If you actually need the wrapper object Blas, then you should have a constructor marked with @JsonCreator accepting the a List<Bla> marked with @JsonProperty (There are other ways, but this is a fail safe way and makes the code readable) 如果您确实需要包装对象Blas,则应该有一个标有@JsonCreator的构造函数, @JsonCreator接受一个标有@JsonCreatorList<Bla> (还有其他方法,但这是一种故障保护方法,可以使代码易于读取)

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

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