使用Jackson或其替代方法将JSON树解析为普通类

时间:2013-03-27 13:24:05

标签: java json jackson

如何解析JSON:

{
    "foo": {
        "bar": {
            "baz": "Hello"
        },
        "qux": "World"
    }
}

使用Jackson或其替代方法进入该类:

public class Foo {
    private String baz;
    private String qux;

    public String getBaz() {
        return baz;
    }

    public void setBaz(final String baz) {
        this.baz = baz;
    }

    public String getQux() {
        return qux;
    }

    public void setQux(final String qux) {
        this.qux = qux;
    }
}

期待如下:

@JsonProperty("foo.bar.baz")
private String baz;
@JsonProperty("foo.qux")
private String qux;

2 个答案:

答案 0 :(得分:3)

我发现,Jackson尚未实现此功能,请参阅issue

作为一种解决方法,可以将以下方法添加到Foo类:

@JsonProperty("foo")
public void setFoo(JsonNode jsonNode) {
    this.qux = jsonNode.get("qux").getTextValue();
    this.baz = jsonNode.get("bar").get("baz").getTextValue();
}

答案 1 :(得分:1)

注意:我是EclipseLink JAXB (MOXy)主管,是JAXB (JSR-222)专家组的成员。

这个用例可能不适用于Jackson,但可以在MOXy用作JSON绑定提供程序时完成。

<强>富

您可以利用MOXy基于路径的映射来完成此用例。

import org.eclipse.persistence.oxm.annotations.XmlPath;

public class Foo {

    private String baz;
    private String qux;

    @XmlPath("foo/bar/baz/text()")
    public String getBaz() {
        return baz;
    }

    public void setBaz(final String baz) {
        this.baz = baz;
    }

    @XmlPath("foo/qux/text()")
    public String getQux() {
        return qux;
    }

    public void setQux(final String qux) {
        this.qux = qux;
    }

}

<强>演示

JAXB运行时API用于读/写JSON。

import java.util.*;
import javax.xml.bind.*;
import javax.xml.transform.stream.StreamSource;
import org.eclipse.persistence.jaxb.JAXBContextProperties;

public class Demo {

    public static void main(String[] args) throws Exception {
        Map<String, Object> properties = new HashMap<String, Object>(2);
        properties.put(JAXBContextProperties.MEDIA_TYPE, "application/json");
        properties.put(JAXBContextProperties.JSON_INCLUDE_ROOT, false);
        JAXBContext jc = JAXBContext.newInstance(new Class[] {Foo.class}, properties);

        Unmarshaller unmarshaller = jc.createUnmarshaller();
        StreamSource json = new StreamSource("src/forum15659950/input.json");
        Foo foo = unmarshaller.unmarshal(json, Foo.class).getValue();

        Marshaller marshaller = jc.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        marshaller.marshal(foo, System.out);
    }

}

<强> input.json /输出

{
   "foo" : {
      "bar" : {
         "baz" : "Hello"
      },
      "qux" : "World"
   }
}

了解更多信息