[英]Parse JSON tree to plain class using Jackson or its alternatives
How to parse that JSON: 如何解析那个JSON:
{
"foo": {
"bar": {
"baz": "Hello"
},
"qux": "World"
}
}
Into that class using Jackson or its alternatives: 使用杰克逊或其替代品进入该类:
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;
}
}
Expecting something like: 期待像:
@JsonProperty("foo.bar.baz")
private String baz;
@JsonProperty("foo.qux")
private String qux;
I have found, that this feature is not implemented in Jackson yet, see issue . 我发现,这个功能尚未在Jackson中实现,请参阅问题 。
As a workaround, method below can be added into Foo
class: 作为一种解决方法,下面的方法可以添加到
Foo
类中:
@JsonProperty("foo")
public void setFoo(JsonNode jsonNode) {
this.qux = jsonNode.get("qux").getTextValue();
this.baz = jsonNode.get("bar").get("baz").getTextValue();
}
Note: I'm the EclipseLink JAXB (MOXy) lead and a member of the JAXB (JSR-222) expert group. 注意:我是EclipseLink JAXB(MOXy)的负责人,也是JAXB(JSR-222)专家组的成员。
This use case may not be possible with Jackson, but can be done when MOXy is used as your JSON-binding provider. Jackson可能无法使用此用例,但可以在将MOXy用作JSON绑定提供程序时完成。
Foo 富
You can take advantage of MOXy's path based mapping for this use case. 您可以利用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;
}
}
Demo 演示
The JAXB runtime APIs are used to read/write the JSON. 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/Output input.json /输出
{
"foo" : {
"bar" : {
"baz" : "Hello"
},
"qux" : "World"
}
}
For More Information 欲获得更多信息
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.