是否有一个库可以将 Java POJO 与 JSON 和 XML 相互转换?

发布于 2024-07-15 05:03:39 字数 1539 浏览 5 评论 0原文

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(10

木落 2024-07-22 05:03:39

GSON 来自 google:http://code.google.com/p /google-gson/

Spring 中使用的 Jackson 库:https: //github.com/FasterXML/jackson

我同意其他人建议使用 jaxb 将 XML 转换为 pojo,它支持很多工具:它是标准。

GSON from google : http://code.google.com/p/google-gson/,

or

Jackson the library used in spring :https://github.com/FasterXML/jackson

and I would concur with others suggesting jaxb for XML to pojo, well supported lots of tools : its the standard.

关于从前 2024-07-22 05:03:39

对于 POJO 到 XML,我建议使用 JAXB (还有其他库也是如此,例如 XStream,但 JAXB 是标准化的)。

对于 JSON 我什么都不知道,但是如果你想实现 RESTful API,你可能会对 JSR-311 为 RESTful API 和 Jersey 定义服务器端 API ,这是它的参考实现。

For POJO to XML I suggest using JAXB (there are other libraries as well, such as XStream for example, but JAXB is standardized).

For JSON I don't know anything, but if you want to implement a RESTful API, you might be interested in JSR-311 which defines a server-side API for RESTful APIs and Jersey, which is its reference implementation.

一向肩并 2024-07-22 05:03:39

使用 Xstream http://x-stream.github.io/ 处理 xml 和 JSON http://www.json.org/java/ 用于 JSON。 我认为没有一个图书馆可以同时完成这两件事。

或者根据您的需要编写一个委托给 XStream 渲染器/JSON 渲染器的包装器。

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.

Or write a wrapper which delegates to XStream renderers/JSON renderers depending on what you want.

々眼睛长脚气 2024-07-22 05:03:39

我认为您可能正在寻找与此处类似的内容: JSON.org Java 部分

I think you may be looking for something similar to what is here: JSON.org Java section

七秒鱼° 2024-07-22 05:03:39

注意:我是EclipseLink JAXB (MOXy) 的领导者和 JAXB (JSR-222) 的成员专家组。

EclipseLink JAXB (MOXy) 支持使用相同的元数据将单个对象模型映射到 XML 和 JSON:

许可证信息


域模型

下面是我们将在本示例中使用的域模型。 对于此示例,我仅使用标准 JAXB (JSR-222) 注释,自 Java SE 6 起,这些注释在 JDK/JRE 中可用。

客户

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;

}

< strong>PhoneNumber

package forum658936;

import javax.xml.bind.annotation.*;

@XmlAccessorType(XmlAccessType.FIELD)
public class PhoneNumber {

    @XmlAttribute
    int id;

    @XmlValue
    String number;

}

jaxb.properties

要将 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

input.xml

这是我们的演示代码将读入并转换为域对象的 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>

关于 XML 的注意事项:


JSON

输出

下面是运行演示代码时输出的 JSON。

{
   "firstName" : "Jane",
   "lastName" : null,
   "phone-number" : [ {
      "id" : 123,
      "value" : "555-1234"
   } ]
}

JSON 需要注意的事项:

  • null 值用于表示 lastName 为 null。 不存在 xsi:nil 属性。
  • 电话号码集合的大小为 1,并且正确地用方括号括起来。 许多库错误地将大小为 1 的集合视为 JSON 对象。
  • int 类型的 property 已正确编组,不带引号。
  • 在 XML 表示中,id 是一个属性,但在 JSON 表示中,不需要专门表示它。

演示代码

在下面的演示代码中,我们将把 XML 文档转换为对象,然后将这些相同的实例转换为 JSON。

演示

MOXy 不仅解释 JAXB 注释,它还是 JAXB 实现,因此使用标准 JAXB 运行时 API。 通过在 Marshaller 上指定 MOXy 指定属性来启用 JSON 绑定。

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);
    }

}

Note: I'm the EclipseLink JAXB (MOXy) lead and a member of the JAXB (JSR-222) expert group.

EclipseLink JAXB (MOXy) supports mapping a single object model to both XML and JSON with the same metadata:

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.

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

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).

javax.xml.bind.context.factory=org.eclipse.persistence.jaxb.JAXBContextFactory

XML

input.xml

This is the XML that our demo code will read in and convert to domain objects.

<?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:


JSON

Output

Below is the JSON that was output by running the demo code.

{
   "firstName" : "Jane",
   "lastName" : null,
   "phone-number" : [ {
      "id" : 123,
      "value" : "555-1234"
   } ]
}

Things to note about the JSON:

  • The null value is used to represent that the lastName is null. There is no presence of the xsi: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 type int 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.

DEMO CODE

In the demo code below we will convert an XML document to objects, and then convert those same instances to 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.

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);
    }

}
葬﹪忆之殇 2024-07-22 05:03:39

Json-lib 根据 Apache 2.0 许可证获得许可。

它还可以将 JSON 对象转换为 XML,但您需要首先通过它将 POJO 转换为 JSON。

Json-lib is licensed under the Apache 2.0 license.

It can also transform JSON objects to XML, but you'd need to convert your POJOs to JSON through it first.

雄赳赳气昂昂 2024-07-22 05:03:39

就我个人而言,我会分别处理这两个问题; 并通过 JSON<-> 转换 JSON<->XML 波乔<-> XML。

这样:Java<->POJO 与 JAXB (http://jaxb.dev.java.net; 也与 JDK 1.6 捆绑在一起),带有注释(XStream 也可以); 对于 JSON,Jackson 的 ObjectMapper (http://jackson.codehaus.org/Tutorial)。 与 Jersey 配合得很好,我自己也使用它(默认情况下,当前的 Jersey 版本不会捆绑完整的 Pojo 数据绑定,但在不久的将来会)

我实际上不会使用任何 xml 库来生成“json”:XStream 和 JAXB/ Jettison 可以生成某种 JSON,但它使用了相当不直观的丑陋约定。

编辑(2011 年 7 月 18 日):Jackson 实际上有一个名为“jackson-xml-databind< /a>”可以读/写XML,类似于JAXB。 因此它可用于 JSON 和 XML,往返于 POJO。

Personally I would tackle the two separately; and to convert JSON<->XML via JSON<-> Pojo <-> 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, Jackson's ObjectMapper (http://jackson.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)

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.

EDIT (18-Jul-2011): Jackson actually has an extension called "jackson-xml-databind" that can read/write XML, similar to JAXB. So it can be used for both JSON and XML, to/from POJOs.

梦魇绽荼蘼 2024-07-22 05:03:39

最后我在网站上看到,XStream 可以做到这两点。 它支持 XML 和 JSON 作为序列化目标。

Last I saw on the website, XStream will do both. It supports XML and JSON as serialization targets.

孤独陪着我 2024-07-22 05:03:39

几乎有数百个。 我最喜欢的是 GSON for POJO <-> POJO <-> 的 JSON 和castor-xml XML。

作为奖励,两者均根据 Apache License 2.0 样式许可证获得许可。

There are almost literally hundreds. My favorites are GSON for POJO <-> JSON and castor-xml for POJO <-> XML.

As a bonus both are licensed under Apache License 2.0 style licenses.

旧故 2024-07-22 05:03:39

查看 Genson 库 http://code.google.com/p/genson/wiki /入门

它易于使用、高性能,并且在设计时就考虑到了扩展性。
实际上它进行 json/java 转换,但不进行 xml 转换。 不过,未来版本可能会添加 xml 支持。

我在泽西岛的 Web 应用程序和 REST Web 服务中使用它,但在某些情况下也将其 json 形式的对象存储到数据库中。

啊,它是在 Apache 2.0 许可证下的。

Have a look at Genson library 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.

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.

Ah and it's under Apache 2.0 license.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文