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

我正在尝试将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"
}

我需要在这里取点地图,因为将有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时如何忽略此映射名称吗?

注意:我正在使用的实际对象具有类似的结构,有点复杂,这里我只是发布一个原型.

最佳答案

如果您事先不知道按键,请使用@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);
  }

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值