使用Jackson或其替代方法将JSON树解析为普通类 [英] Parse JSON tree to plain class using Jackson or its alternatives
本文介绍了使用Jackson或其替代方法将JSON树解析为普通类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何解析JSON:
{
"foo": {
"bar": {
"baz": "Hello"
},
"qux": "World"
}
}
使用 Jackson 进入该班级或其替代方案:
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;
推荐答案
注意:我' EclipseLink JAXB(MOXy) 负责人及其成员 JAXB(JSR-222) 专家组。
Note: I'm the EclipseLink JAXB (MOXy) lead and a member of the JAXB (JSR-222) expert group.
Jackson可能无法使用此用例,但可以在MOXy用作JSON绑定提供程序时完成。
This use case may not be possible with Jackson, but can be done when MOXy is used as your JSON-binding provider.
Foo
您可以利用MOXy基于路径的映射来处理此用例。
You can take advantage of MOXy's path based mapping for this use case.
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。
The JAXB runtime APIs are used to read/write the 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"
}
}
更多信息
- http://blog.bdoughan.com/2011/05/specifying- eclipselink-moxy-as-your.html
- http://blog.bdoughan.com/2011/08/json-binding-with-eclipselink-moxy.html
- http://blog.bdoughan.com/2011/05/specifying-eclipselink-moxy-as-your.html
- http://blog.bdoughan.com/2011/08/json-binding-with-eclipselink-moxy.html
这篇关于使用Jackson或其替代方法将JSON树解析为普通类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文