簡體   English   中英

使用Jackson或其替代方法將JSON樹解析為普通類

[英]Parse JSON tree to plain class using Jackson or its alternatives

如何解析那個JSON:

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

使用傑克遜或其替代品進入該類:

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;

我發現,這個功能尚未在Jackson中實現,請參閱問題

作為一種解決方法,下面的方法可以添加到Foo類中:

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

注意:我是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"
   }
}

欲獲得更多信息

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM