使用Jackson将具有int属性的对象数组反序列化为int数组

时间:2018-09-06 14:29:19

标签: json jackson

我有以下JSON ...

{
  "name":"MyThings",
  "things":[
    {
      "num":"123"
    },
    {
      "num":"456"
    }
  ]
}

到目前为止,我有很多映射...

@JsonIgnoreProperties(ignoreUnknown = true)
public class ThingList {
    private String name;
    private int[] nums;
}

基本上我该如何使用杰克逊将对象数组映射为整数数组?

1 个答案:

答案 0 :(得分:1)

您可以为此使用自定义反序列化器:

class DeSerializer extends StdDeserializer<ThingList> {

  protected DeSerializer() {
    super(ThingList.class);
  }

  @Override
  public ThingList deserialize(JsonParser p, DeserializationContext ctxt) {
    // use p.getText() and p.nextToken to navigate through the xml and construct ThingList object
    return something;
  }

使用反序列化器按如下所示初始化解析器:

ObjectMapper mapper = new ObjectMapper();
SimpleModule module = new SimpleModule("configModule", Version.unknownVersion());
module.addDeserializer(ThingList.class, new DeSerializer());
mapper.registerModule(module);
ThingList tl = mapper.readValue(<json string>, ThingList.class);