1

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 ?

Seb
  • 3,602
  • 8
  • 36
  • 52

1 Answers1

8

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
}
cassiomolin
  • 124,154
  • 35
  • 280
  • 359