将 JSON 子对象属性绑定到 Jackson 中的 Java 对象字段

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4199794/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 05:17:20  来源:igfitidea点击:

Binding JSON child object property into Java object field in Hymanson

javajsondata-bindingHymanson

提问by hleinone

I have a JSON object, say:

我有一个 JSON 对象,例如:

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

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

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

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

How can I set the value of foo.barfrom JSON to the barfield in the FooJava object?

如何将foo.barJSON的值设置barFooJava 对象中的字段?

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

我试过用 注释该字段@JsonProperty("foo.bar"),但它不能那样工作。

回答by hleinone

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");
}

回答by StaxMan

There is no automated functionality for this (as far as I know), but this is a somewhat often requested feature; there is this Jira RFE: http://jira.codehaus.org/browse/HymanSON-132that sounds like what you are looking for.

这没有自动化功能(据我所知),但这是一个经常被要求的功能;有这个 Jira RFE:http: //jira.codehaus.org/browse/HymanSON-132听起来像你正在寻找的。

回答by Wilson Soethe Cursino

Here a quick example that works:

这是一个有效的快速示例:

JSON:

JSON:

[{"function":{"name":"Function 1"}},
 {"function":{"name":"Function 2"}}]

Java:

爪哇:

import java.util.Map;

import javax.xml.bind.annotation.XmlRootElement;

import lombok.Getter;
import lombok.Setter;
import lombok.ToString;

import org.codehaus.Hymanson.annotate.JsonIgnoreProperties;
import org.codehaus.Hymanson.annotate.JsonProperty;
@Getter
@Setter
@ToString
@JsonIgnoreProperties(ignoreUnknown = true)
public class Function {
    @JsonProperty("name")
    private String name;

    @JsonProperty("function")
    public void setFunction(Map<String, Object> function) {
      name = (String) function.get("name");
    }
}

回答by Dennis

That's like binding an apple to an orange! Another 'catchy phrase' would be, "Impedance Mismatch", or in Star Trek 1, "Non Sequetor!" Bind it a MATCHED object, then do new assignment in Java between the different kinds of objects.

这就像把一个苹果绑在一个橙子上!另一个“朗朗上口的短语”是“阻抗不匹配”,或者在《星际迷航 1》中,“Non Sequetor!” 将它绑定一个 MATCHED 对象,然后在 Java 中在不同类型的对象之间进行新的赋值。