是否有一个库可以将 Java POJO 与 JSON 和 XML 相互转换?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/658936/
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
Is there a library to convert Java POJOs to and from JSON and XML?
提问by Darren Hague
I have an object graph that I would like to convert to and from JSON and XML, for the purposes of creating a REST-style API. It strikes me that someone must have done this already, but a quick search using Google and Stack Overflow reveals nothing.
我有一个对象图,为了创建 REST 风格的 API,我想在 JSON 和 XML 之间进行转换。我觉得肯定有人已经这样做了,但是使用 Google 和 Stack Overflow 进行快速搜索并没有发现任何信息。
Does anyone know of a suitable (Apache or equivalent license preferred) library to do this?
有谁知道一个合适的(Apache 或同等许可证首选)库来做到这一点?
回答by Mr. Will
I think you may be looking for something similar to what is here: JSON.org Java section
我认为您可能正在寻找类似于此处的内容:JSON.org Java 部分
回答by Joachim Sauer
For POJO to XML I suggest using JAXB(there are other libraries as well, such as XStream for example, but JAXB is standardized).
对于 POJO 到 XML,我建议使用JAXB(还有其他库,例如 XStream,但 JAXB 是标准化的)。
For JSON I don't know anything, but if you want to implement a RESTful API, you might be interested in JSR-311which defines a server-side API for RESTful APIs and Jersey, which is its reference implementation.
对于 JSON 我什么都不知道,但是如果你想实现一个 RESTful API,你可能会对JSR-311感兴趣,它为 RESTful API 和Jersey定义了一个服务器端 API ,这是它的参考实现。
回答by Powerlord
回答by Kannan Ekanath
Use Xstream http://x-stream.github.io/for xml and JSON http://www.json.org/java/for JSON. I dont think there is one library that does both.
对 xml使用 Xstream http://x-stream.github.io/,对 JSON使用JSON http://www.json.org/java/。我不认为有一个图书馆可以同时做到这两点。
Or write a wrapper which delegates to XStream renderers/JSON renderers depending on what you want.
或者编写一个包装器,根据您的需要委托给 XStream 渲染器/JSON 渲染器。
回答by StaxMan
Personally I would tackle the two separately; and to convert JSON<->XML via JSON<-> Pojo <-> XML.
我个人会分别处理这两个问题;并通过 JSON<-> Pojo <-> XML 转换 JSON<->XML。
With that: Java<->POJO with JAXB (http://jaxb.dev.java.net; also bundled with JDK 1.6) with annotations (XStream is ok too); and for JSON, Hymanson's ObjectMapper (http://Hymanson.codehaus.org/Tutorial). Works nicely with Jersey, and I am use it myself (current Jersey version does not bundle full Pojo data binding by default, but will in near future)
有了这个:Java<->POJO with JAXB(http://jaxb.dev.java.net;也与 JDK 1.6 捆绑在一起)和注释(XStream 也可以);对于 JSON,Hymanson 的 ObjectMapper ( http://Hymanson.codehaus.org/Tutorial)。与 Jersey 配合得很好,我自己也在使用它(当前 Jersey 版本默认不捆绑完整的 Pojo 数据绑定,但在不久的将来会)
I would actually not use any of xml libs to produce "json": XStream and JAXB/Jettison can produce kind of JSON, but it uses ugly conventions that are rather non-intuitive.
我实际上不会使用任何 xml 库来生成“json”:XStream 和 JAXB/Jettison 可以生成某种 JSON,但它使用了相当不直观的丑陋约定。
EDIT (18-Jul-2011): Hymanson actually has an extension called "Hymanson-xml-databind" that can read/write XML, similar to JAXB. So it can be used for both JSON and XML, to/from POJOs.
编辑(2011 年 7 月 18 日):Hymanson 实际上有一个名为“ Hymanson-xml-databind”的扩展,它可以读/写 XML,类似于 JAXB。因此它可以用于 JSON 和 XML,以及往/返 POJO。
回答by Jay R.
Last I saw on the website, XStream will do both. It supports XML and JSON as serialization targets.
上次我在网站上看到,XStream 可以同时执行这两项操作。它支持 XML 和 JSON 作为序列化目标。
回答by NimChimpsky
GSONfrom google : http://code.google.com/p/google-gson/,
来自谷歌的GSON:http: //code.google.com/p/google-gson/,
or
或者
Hymansonthe library used in spring :https://github.com/FasterXML/Hymanson
Hymanson春季使用的库:https: //github.com/FasterXML/Hymanson
and I would concur with others suggesting jaxb for XML to pojo, well supported lots of tools : its the standard.
我同意其他人建议将 jaxb 用于 XML 到 pojo,它支持很多工具:这是标准。
回答by bdoughan
Note:I'm the EclipseLink JAXB (MOXy)lead and a member of the JAXB (JSR-222)expert group.
注意:我是EclipseLink JAXB (MOXy) 的负责人和JAXB (JSR-222)专家组的成员。
EclipseLink JAXB (MOXy)supports mapping a single object model to both XML and JSON with the same metadata:
EclipseLink JAXB (MOXy)支持将单个对象模型映射到具有相同元数据的 XML 和 JSON:
License Information
许可证信息
DOMAIN MODEL
域模型
Below is the domain model we will use for this example. For this example I'm just using the standard JAXB (JSR-222) annotations which have are available in the JDK/JRE since Java SE 6.
下面是我们将用于此示例的域模型。对于此示例,我仅使用自 Java SE 6 以来在 JDK/JRE 中可用的标准 JAXB (JSR-222) 注释。
Customer
顾客
package forum658936;
import java.util.List;
import javax.xml.bind.annotation.*;
@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class Customer {
String firstName;
@XmlElement(nillable=true)
String lastName;
@XmlElement(name="phone-number")
List<PhoneNumber> phoneNumbers;
}
PhoneNumber
电话号码
package forum658936;
import javax.xml.bind.annotation.*;
@XmlAccessorType(XmlAccessType.FIELD)
public class PhoneNumber {
@XmlAttribute
int id;
@XmlValue
String number;
}
jaxb.properties
jaxb.properties
To specify MOXy as your JAXB provider you need to include a file called jaxb.properties
in the same package as your domain model with the following entry (see: http://blog.bdoughan.com/2011/05/specifying-eclipselink-moxy-as-your.html).
要将 MOXy 指定为您的 JAXB 提供程序,您需要包含一个jaxb.properties
在与域模型相同的包中调用的文件,其中包含以下条目(请参阅:http: //blog.bdoughan.com/2011/05/specifying-eclipselink-moxy-as -your.html)。
javax.xml.bind.context.factory=org.eclipse.persistence.jaxb.JAXBContextFactory
XML
XML
input.xml
输入文件
This is the XML that our demo code will read in and convert to domain objects.
这是我们的演示代码将读取并转换为域对象的 XML。
<?xml version="1.0" encoding="UTF-8"?>
<customer xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<firstName>Jane</firstName>
<lastName xsi:nil="true"/>
<phone-number id="123">555-1234</phone-number>
</customer>
Things to note about the XML:
关于 XML 的注意事项:
- The
xsi:nil
attribute is used to indicate that thelastName
is null. - The
phone-number
element is a complex type with simple content (see: http://blog.bdoughan.com/2011/06/jaxb-and-complex-types-with-simple.html).
- 该
xsi:nil
属性用于指示lastName
为空。 - 该
phone-number
元素是具有简单内容的复杂类型(参见:http: //blog.bdoughan.com/2011/06/jaxb-and-complex-types-with-simple.html)。
JSON
JSON
Output
输出
Below is the JSON that was output by running the demo code.
下面是通过运行演示代码输出的 JSON。
{
"firstName" : "Jane",
"lastName" : null,
"phone-number" : [ {
"id" : 123,
"value" : "555-1234"
} ]
}
Things to note about the JSON:
关于 JSON 的注意事项:
- The
null
value is used to represent that thelastName
is null. There is no presence of thexsi:nil
attribute. - The collect of phone numbers is of size 1 and is correctly bound by square brackets. Many libraries incorrectly treat collections of size 1 as JSON objects.
- The
property
of typeint
was correctly marshalled without quotes. - In the XML representation
id
was an attribute, but in the JSON representation there is not need for it to be specially represented.
- 该
null
值用于表示该lastName
值为空。不存在该xsi:nil
属性。 - 电话号码集合的大小为 1,并由方括号正确绑定。许多库错误地将大小为 1 的集合视为 JSON 对象。
- 该
property
类型的int
正确编组没有引号。 - 在 XML 表示中
id
是一个属性,但在 JSON 表示中不需要专门表示它。
DEMO CODE
演示代码
In the demo code below we will convert an XML document to objects, and then convert those same instances to JSON.
在下面的演示代码中,我们将一个 XML 文档转换为对象,然后将这些相同的实例转换为 JSON。
Demo
演示
MOXy doesn't just interpret JAXB annotations it is a JAXB implementation so the standard JAXB runtime APIs are used. JSON binding is enabled by specifying MOXy specify properties on the Marshaller
.
MOXy 不只是解释 JAXB 注释,它是一个 JAXB 实现,因此使用标准的 JAXB 运行时 API。JSON 绑定是通过在Marshaller
.
package forum658936;
import java.io.File;
import javax.xml.bind.*;
import org.eclipse.persistence.jaxb.MarshallerProperties;
public class Demo {
public static void main(String[] args) throws Exception {
JAXBContext jc = JAXBContext.newInstance(Customer.class);
Unmarshaller unmarshaller = jc.createUnmarshaller();
File xml = new File("src/forum658936/input.xml");
Customer customer = (Customer) unmarshaller.unmarshal(xml);
Marshaller marshaller = jc.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.setProperty(MarshallerProperties.MEDIA_TYPE, "application/json");
marshaller.setProperty(MarshallerProperties.JSON_INCLUDE_ROOT, false);
marshaller.marshal(customer, System.out);
}
}
回答by eugen
Have a look at Genson library http://code.google.com/p/genson/wiki/GettingStarted.
查看 Genson 库http://code.google.com/p/genson/wiki/GettingStarted。
It is easy to use, performant and was designed with extension in mind. Actually it does json/java conversion but not xml. However xml support may be added in a future version.
它易于使用、高性能,并且在设计时考虑到了扩展性。实际上它进行 json/java 转换,而不是 xml。但是,将来的版本中可能会添加 xml 支持。
I'm using it in web applications and REST web services in jersey, but also in some cases to store objects in their json form into a database.
我在 web 应用程序和 jersey 中的 REST web 服务中使用它,但在某些情况下也将其 json 形式的对象存储到数据库中。
Ah and it's under Apache 2.0 license.
啊,它在 Apache 2.0 许可下。
回答by Mikkel L?kke
There are almost literally hundreds. My favorites are GSON for POJO <-> JSON and castor-xml for POJO <-> XML.
几乎字面上有数百个。我最喜欢的是用于 POJO <-> JSON 的 GSON 和用于 POJO <-> XML 的 castor-xml。
As a bonus both are licensed under Apache License 2.0 style licenses.
作为奖励,两者都在 Apache License 2.0 样式许可下获得许可。