繁体   English   中英

@jsonanygetter 不起作用

[英]@jsonanygetter doesn't work

假设,我有以下课程:

@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"}}

我做错了什么? 以及如何得到预期的结果?

确保ObjectMapper@JsonAnySetter / @JsonAnyGetter注释来自相同的包。

都应该是:

  • 要么来自org.codehaus.jackson - 这是 jackson 的旧版本
  • 或来自com.fasterxml.jackson - 这是较新的(Jackson 在发布 Jackson 2 时已从 Codehaus 迁移 - 参见此处

如果您的项目中有这两个依赖项,并且您交替使用它们,您可能很难注意到问题。

最好的办法是从你的项目依赖中去掉org.codehaus.jackson

可能会迟到,但考虑发布答案,因为它可能对将来的某人有所帮助。

这是您可以为您的班级相应配置的示例代码。

将读取 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;
    }
}

如果您使用ObjectMapperreadValue ,即使对于 JSON 中的重复键,这也将起作用,但是如果您使用ObjectMappertreeToValue方法,那么这对于重复键将失败,并且您将只有重复字段的最后一个值。 我仍在想办法在使用treeToValue方法时访问重复字段

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM