java - 如何在使用 Jackson 将 json 转换为 Java 对象时忽略 Map 相关的大括号

标签 java jackson jackson-databind

我正在尝试将 JSON 转换为 Java 对象,但我很难构建 Java 等效对象。

我的 JSON 看起来像这样

{
    "point1": {
        "x": 1.0,
        "y": 2.0
    },
    "point2": {
        "x": 1.0,
        "y": 2.0
    },
    "point3": {
        "x": 1.0,
        "y": 2.0
    },
    "customobject1": "cust1",
    "customobject2": "cust2"
}

我需要在这里取 map 来获取点,因为会有n个点,

public class Test {

    public String getCustomobject1() {
        return customobject1;
    }

    public void setCustomobject1(String customobject1) {
        this.customobject1 = customobject1;
    }

    public String getCustomobject2() {
        return customobject2;
    }

    public void setCustomobject2(String customobject2) {
        this.customobject2 = customobject2;
    }

    Map<String, Point> testing  = new HashMap<>();

    String customobject1;
    String customobject2; 

    public Map<String, Point> getTesting() {
        return testing;
    }

    public void setTesting(Map<String, Point> testing) {
        this.testing = testing;
    }

}

但是我遇到了无法识别的属性异常,我知道有一个额外的包装器 ({}) 导致了这个问题,有人可以建议我如何在反序列化 JSON 时忽略这个 map 名称吗?

注意:我工作的实际对象有点复杂,结构相似,我在这里只发布一个原型(prototype)。

最佳答案

如果您事先不知道 key ,请使用 @JsonAnySetter映射它们:

Marker annotation that can be used to define a non-static, two-argument method (first argument name of property, second value to set), to be used as a "fallback" handler for all otherwise unrecognized properties found from JSON content. It is similar to XmlAnyElement in behavior; and can only be used to denote a single property per type.

If used, all otherwise unmapped key-value pairs from JSON Object values are added to the property (of type Map or bean).

public class Test  {
  private Map<String, Point> points = new HashMap<>();

  @JsonAnySetter
  public void setPoints(String name, Point value) {
    points.put(name, value);
  }

}

关于java - 如何在使用 Jackson 将 json 转换为 Java 对象时忽略 Map 相关的大括号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54933458/

相关文章:

java - 在java中读取unicode txt

java - 在 Eclipse 中调试 List<Class> 对象?

java - Android 的监听器构造可以在 Windows Phone 中使用吗?

java - 如何使用matlab编译器sdk编译类?

json - 基于 Spring 安全角色的 Jackson @JsonIgnore 字段

java - jackson 将数组反序列化为 java 对象

java - 不存在像默认构造函数这样的创建者,无法从对象值反序列化(没有基于委托(delegate)或属性的创建者)

java - 使用 Jackson 将名称值对数组反序列化为对象

Spring Cloud Stream @StreamListener 自定义 MappingJackson2MesageConverter

java - SpringBoot反序列化无默认构造函数