是否有一个库可以将Java pojo转换为JSON和XML?

时间:2021-09-07 23:44:28

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.

我有一个对象图,我想要在JSON和XML之间进行转换,以便创建rest样式的API。我觉得一定有人已经这样做了,但是使用谷歌和Stack Overflow进行快速搜索并没有发现什么。

Does anyone know of a suitable (Apache or equivalent license preferred) library to do this?

有谁知道合适的(Apache或同等的许可证优先)库来实现这个目的吗?

10 个解决方案

#1


12  

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

来自谷歌的GSON: http://code.google.com/p/goog -gson/,

or

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

Jackson: 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.

我也同意其他人关于jaxb对pojo的建议,它支持很多工具:它是标准。

#2


10  

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-311 which defines a server-side API for RESTful APIs and Jersey, which is its reference implementation.

对于JSON,我什么都不知道,但是如果您想实现RESTful API,您可能会对JSR-311感兴趣,它为RESTful API定义了服务器端API,而Jersey是它的引用实现。

#3


6  

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.

使用Xstream http://x-stream.github。io/表示xml和JSON http://www.json.org/java/表示JSON。我不认为有一个图书馆可以做到这两点。

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

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

#4


3  

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

我认为您可能正在寻找类似于这里的东西:JSON.org Java部分

#5


3  

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

注意:我是eclipse 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.

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

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

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的文件。属性在与域模型相同的包中,包含以下条目(参见: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

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 the lastName is null.
  • nil属性用于表示lastName为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).
  • 电话号码元素是一个包含简单内容的复杂类型(参见:http://blog.bdoughan.com/2011/06/jaxband -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 the lastName is null. There is no presence of the xsi:nil attribute.
  • null值用于表示lastName为null。不存在xsi:nil属性。
  • 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.
  • 电话号码的收集是1号的,并且正确地用方括号括起来。许多库不正确地将大小为1的集合视为JSON对象。
  • The property of type int was correctly marshalled without quotes.
  • int类型的属性被正确地编组,没有引号。
  • In the XML representation id was an attribute, but in the JSON representation there is not need for it to be specially represented.
  • 在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。通过在封送器上指定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);
    }

}

#6


1  

Json-lib is licensed under the Apache 2.0 license.

Json-lib是在Apache 2.0许可下授权的。

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

它还可以将JSON对象转换为XML,但是首先需要将pojo转换为JSON。

#7


1  

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

有了这个:Java<->和JAXB的POJO (http://jaxb.dev.java.net;也与JDK 1.6绑定)和注释(XStream也可以);JSON是Jackson的ObjectMapper (http://jackson.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 libs来生成“json”:XStream和JAXB/Jettison可以生成某种json,但它使用的是相当不直观的丑陋约定。

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.

编辑(18-Jul-2011): Jackson实际上有一个名为“Jackson - XML -databind”的扩展,可以读写XML,类似于JAXB。因此,它可以用于JSON和XML,也可以用于pojo。

#8


0  

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

上次我在网站上看到,XStream将两者都做。它支持XML和JSON作为序列化目标。

#9


0  

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许可2.0风格许可下获得许可的。

#10


-1  

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.

我在jersey的web应用程序和REST web服务中使用它,但在某些情况下,我也使用它将json格式的对象存储到数据库中。

Ah and it's under Apache 2.0 license.

它在Apache 2.0许可下。

#1


12  

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

来自谷歌的GSON: http://code.google.com/p/goog -gson/,

or

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

Jackson: 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.

我也同意其他人关于jaxb对pojo的建议,它支持很多工具:它是标准。

#2


10  

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-311 which defines a server-side API for RESTful APIs and Jersey, which is its reference implementation.

对于JSON,我什么都不知道,但是如果您想实现RESTful API,您可能会对JSR-311感兴趣,它为RESTful API定义了服务器端API,而Jersey是它的引用实现。

#3


6  

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.

使用Xstream http://x-stream.github。io/表示xml和JSON http://www.json.org/java/表示JSON。我不认为有一个图书馆可以做到这两点。

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

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

#4


3  

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

我认为您可能正在寻找类似于这里的东西:JSON.org Java部分

#5


3  

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

注意:我是eclipse 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.

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

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

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的文件。属性在与域模型相同的包中,包含以下条目(参见: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

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 the lastName is null.
  • nil属性用于表示lastName为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).
  • 电话号码元素是一个包含简单内容的复杂类型(参见:http://blog.bdoughan.com/2011/06/jaxband -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 the lastName is null. There is no presence of the xsi:nil attribute.
  • null值用于表示lastName为null。不存在xsi:nil属性。
  • 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.
  • 电话号码的收集是1号的,并且正确地用方括号括起来。许多库不正确地将大小为1的集合视为JSON对象。
  • The property of type int was correctly marshalled without quotes.
  • int类型的属性被正确地编组,没有引号。
  • In the XML representation id was an attribute, but in the JSON representation there is not need for it to be specially represented.
  • 在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。通过在封送器上指定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);
    }

}

#6


1  

Json-lib is licensed under the Apache 2.0 license.

Json-lib是在Apache 2.0许可下授权的。

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

它还可以将JSON对象转换为XML,但是首先需要将pojo转换为JSON。

#7


1  

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

有了这个:Java<->和JAXB的POJO (http://jaxb.dev.java.net;也与JDK 1.6绑定)和注释(XStream也可以);JSON是Jackson的ObjectMapper (http://jackson.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 libs来生成“json”:XStream和JAXB/Jettison可以生成某种json,但它使用的是相当不直观的丑陋约定。

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.

编辑(18-Jul-2011): Jackson实际上有一个名为“Jackson - XML -databind”的扩展,可以读写XML,类似于JAXB。因此,它可以用于JSON和XML,也可以用于pojo。

#8


0  

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

上次我在网站上看到,XStream将两者都做。它支持XML和JSON作为序列化目标。

#9


0  

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许可2.0风格许可下获得许可的。

#10


-1  

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.

我在jersey的web应用程序和REST web服务中使用它,但在某些情况下,我也使用它将json格式的对象存储到数据库中。

Ah and it's under Apache 2.0 license.

它在Apache 2.0许可下。