Java Jackson映射中标准和动态特性的混合

Java Jackson映射中标准和动态特性的混合,java,json,jackson,Java,Json,Jackson,我们正在使用一个提供json的REST服务,该服务将包括一些标准属性以及一些动态属性 例如: { id: 123, name: "some name", custom_name: "Some value", some_other_custom_name: "Some other value", } 理想情况下,我希望课程设计如下: public class MyObject{ @JsonProperty int id; @JsonProperty String name

我们正在使用一个提供json的REST服务,该服务将包括一些标准属性以及一些动态属性

例如:

{
  id: 123,
  name: "some name",
  custom_name: "Some value",
  some_other_custom_name: "Some other value",
}
理想情况下,我希望课程设计如下:

public class MyObject{
  @JsonProperty int id;
  @JsonProperty String name;
  private Map<String, String> customVals;

  public int getId(){
    return id;
  }

  public String getName(){
    return name;
  }

  public String getCustomVal(String key){
    return customVals.get(key);
  }
}
公共类MyObject{
@JsonProperty int-id;
@JsonProperty字符串名称;
私人地图定制;
公共int getId(){
返回id;
}
公共字符串getName(){
返回名称;
}
公共字符串getCustomVal(字符串键){
返回customVals.get(键);
}
}
有没有办法说服Jackson将自定义值推送到映射中(或实现等效功能)

现在,我只是将整个对象反序列化为一个映射,并将其包装到我的业务对象中,但如果反序列化能够处理它,它就没有那么优雅了。

您可以使用Jackson

下面是一个完整的示例:

public class JacksonAnyGetter {

    static final String JSON = "{"
            + "  \"id\": 123,"
            + "  \"name\": \"some name\","
            + "  \"custom_name\": \"Some value\","
            + "  \"some_other_custom_name\": \"Some other value\""
            + "}";

    static class Bean {
        public int id;
        public String name;
        private Map<String, Object> properties = new HashMap<>();

        @JsonAnySetter
        public void add(String key, String value) {
            properties.put(key, value);
        }

        @JsonAnyGetter
        public Map<String, Object> getProperties() {
            return properties;
        }

        @Override
        public String toString() {
            return "Bean{" +
                    "id=" + id +
                    ", name='" + name + '\'' +
                    ", properties=" + properties +
                    '}';
        }
    }

    public static void main(String[] args) throws IOException {
        final ObjectMapper mapper = new ObjectMapper();
        final Bean bean = mapper.readValue(JSON, Bean.class);
        System.out.println(bean);
        final String json = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(bean);
        System.out.println(json);
    }
}

你不应该添加
@JsonIgnoreProperties({“properties”})
这样属性就不会被添加两次了吗?
Bean{id=123, name='some name', properties={custom_name=Some value, some_other_custom_name=Some other value}}

{
  "id" : 123,
  "name" : "some name",
  "custom_name" : "Some value",
  "some_other_custom_name" : "Some other value"
}