将JSON子对象属性绑定到Jackson中的Java对象字段中 [英] Binding JSON child object property into Java object field in Jackson

查看:424
本文介绍了将JSON子对象属性绑定到Jackson中的Java对象字段中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个JSON对象,说:

I have a JSON object, say:

{
  "foo": {
    "bar": 1
  },
  "baz": 2
}

我想将它绑定到一个Java对象,如:

and I want to bind it into a Java object, like:

@JsonIgnoreProperties(ignoreUnknown = true)
public class Foo {
  private int bar;
  @JsonProperty("baz")
  private int baz;
}

如何设置 foo.bar的值从JSON到 bar 中的 c $ c> foo Java对象

How can I set the value of foo.bar from JSON to the bar field in the Foo Java object?

我尝试使用 @JsonProperty(foo.bar)注释该字段,但它不起作用。

I've tried annotating the field with @JsonProperty("foo.bar"), but it doesn't work like that.

推荐答案

这不是完美的,但这是我能想出来的最优雅的方式。

This ain't perfect but it's the most elegant way I could figure out.

@JsonProperty("foo")
public void setFoo(Map<String, Object> foo) {
  bar = (Integer) foo.get("bar");
}

这篇关于将JSON子对象属性绑定到Jackson中的Java对象字段中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆