我正在尝试使用杰克逊反序列化json,问题是字段名称并不总是相同的,例如
打个电话给我
{
id: "blabla"
aFieldname : { an object if type A}
}
Another call will give me
{
id: "blabla"
anotherName : { the same kind of object }
}
我无法预测该字段的名称。甚至有可能吗?
答案 0 :(得分:3)
您可以将JSON反序列化为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);
或者您可以使用@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);
}
}
如果您知道属性的可能名称,则可以使用@JsonAlias
注释,该注释为introduced in Jackson 2.9:
public class Data {
private String id;
@JsonAlias({ "onePossibleName", "anotherPossibleName" })
private Foo something;
// Getters and setters
}