假设我有以下课程:
@JsonIgnoreProperties(ignoreUnknown = true)
@JsonInclude(JsonInclude.Include.NON_NULL)
public class ObjectOfMonitoring {
private BigInteger id;
private Map<String, Object> properties = new HashMap<>();
@JsonAnySetter
public void add(String key, Object value) {
properties.put(key, value);
}
@JsonAnyGetter
public Map<String, Object> getProperties() {
return properties;
}
我在下面的代码中测试它:
ObjectOfMonitoring objectOfMonitoring = new ObjectOfMonitoring();
objectOfMonitoring.setId(BigInteger.ONE);
objectOfMonitoring.add("key1", "value1");
String jsonInString = mapper.writeValueAsString(objectOfMonitoring);
System.out.println(jsonInString);
我想得到结果:
{"id":1,"key2":"value2","key1":"value1"}
但实际结果是:
{"id":1,"properties":{"key2":"value2","key1":"value1"}}
我做错了什么?以及如何获得预期的结果?
答案 0 :(得分:0)
确保ObjectMapper
和@JsonAnySetter
/ @JsonAnyGetter
批注来自同一包。
所有应为:
org.codehaus.jackson
的任何一个-年龄较大
杰克逊的版本com.fasterxml.jackson
-
较新(在发布Jackson 2时,Jackson已从Codehaus移出-
参见here)如果您的项目中同时具有两个依赖项,并且您可以互换使用它们,那么您可能很难注意到问题。
最好是从项目依赖项中摆脱org.codehaus.jackson
。
答案 1 :(得分:0)
参加聚会可能会迟到,但考虑发布答案,因为它可以在未来对某人有所帮助。
这是您可以为类进行相应配置的示例代码。
将读取 JSON 并与类关联的主类:
public class Main {
public static void main(String[] args) throws Exception {
File jsonFile = new File("test.json").getAbsoluteFile();
final ObjectMapper mapper = new ObjectMapper();
MyObject myObject = mapper.readValue(jsonFile, MyPojo.class);
}
}
您的自定义 POJO:
class MyObject {
private int id;
private Map<String,String> customField;
//Getter and Setter for POJO fields ommited
@JsonAnySetter
public void setCustomField(String key, Object value) {
System.out.println(" Key : " + key + " Value : " + value);
if(customField == null){
customField = new HashMap<String,Object>();
}
customField.put(key,value);
}
@JsonAnyGetter
public Map<String,String> getCustomField(){
return customField;
}
}
如果您使用 readValue
中的 ObjectMapper
,即使对于 JSON 中的重复键,这也将起作用,但是如果您使用 treeToValue
中的 ObjectMapper
方法,那么这重复键将失败,您将只有重复字段的最后一个值。我仍在想办法在使用 treeToValue
方法时访问重复字段