问题
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