简体   繁体   English

使用 jackson 将 singleton json 数组反序列化为相同类型的 pojo?

[英]Deserializing a singleton json array into a pojo of the same type using jackson?

Is there any out of the box way to deserialize a singleton json array into a java pojo of the same type?是否有任何开箱即用的方法可以将 singleton json 数组反序列化为相同类型的 java pojo?

for example, I would like the following json:例如,我想要以下 json:

[{"eventId": "event1", "timestamp": 1232432132}]

to be deserialized into the following java POJO:被反序列化成如下java POJO:

class Event {
  String eventId;
  long timestamp;
}

I tried using the following class:我尝试使用以下 class:

class Event {
  String eventId;
  long timestamp;

  public Event(@JsonProperty("eventId") String event, 
               @JsonProperty("timestamp") long timestamp)
    //fields init
  }

  @JsonCreator
  public Event(List<Event> singletonList)
    //take first element in list and set its fields on this
  } 

but this fails with: om.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot deserialize instance of java.util.ArrayList out of FIELD_NAME token但这失败了: om.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot deserialize instance of java.util.ArrayList out of FIELD_NAME token

I know I can wrap the Event POJO with some other class like this:我知道我可以像这样用其他一些 class 包装 Event POJO:

class EventWrapper {
   Event event;

   @JsonCreator   
   EventWrapper(List<Event> events) {
     this.event = events.get(0);
   }  

but I would like to avoid that (as well as avoid custom deserializer)但我想避免这种情况(以及避免自定义反序列化器)

Any help will be much appreciated.任何帮助都感激不尽。

you can get List by following this, instead of creating additional class,您可以按照此获取列表,而不是创建额外的 class,

    import com.fasterxml.jackson.databind.ObjectMapper;
    ObjectMapper mapper = new ObjectMapper();
    List<Event> myObjects = Arrays.asList(mapper.readValue(json, Event[].class));

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

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