deserialize json using jackson with dynamic field name

北城以北 提交于 2021-02-08 08:21:19

问题


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

One call will give me

{
  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 ?


回答1:


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);

Or you could use @JsonAnySetter:

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
}


来源:https://stackoverflow.com/questions/51079658/deserialize-json-using-jackson-with-dynamic-field-name

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!