使用具有动态字段名称的杰克逊反序列化json [英] deserialize json using jackson with dynamic field name

查看:54
本文介绍了使用具有动态字段名称的杰克逊反序列化json的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用杰克逊反序列化json,问题是字段名称并不总是相同的,例如

I'm trying to deserialize json using jackson, the problem is that field names are not always the same, for instance

打个电话给我

{
  id: "blabla"
  aFieldname : { an object if type A} 
}

Another call will give me 

{
  id: "blabla"
  anotherName : { the same kind of object } 
}

我无法预测该字段的名称.甚至有可能吗?

I can't predict the name of the field. is it even possible ?

推荐答案

您可以将JSON反序列化为Map<String, Object>:

You could deserialize the JSON as a Map<String, Object>:

ObjectMapper mapper = new ObjectMapper();

TypeReference<HashMap<String, Object>> typeReference = 
    new TypeReference<HashMap<String, Object>>() {};
Map<String, Object> data = mapper.readValue(json, typeReference);


或者您可以使用 :

public class Data {

    private String id;
    private Map<String, Object> unknownFields = new HashMap<>();

    // Getters and setters (except for unknownFields)

    @JsonAnySetter
    public void setUnknownField(String name, Object value) {
        unknownFields.put(name, value);
    }
}


如果您知道该属性的可能名称,则可以使用


If you know the possible names of the property, you could use the @JsonAlias annotation, which was introduced in Jackson 2.9:

public class Data {

    private String id;

    @JsonAlias({ "onePossibleName", "anotherPossibleName" })
    private Foo something;

    // Getters and setters
}

这篇关于使用具有动态字段名称的杰克逊反序列化json的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆