Is there a library to convert Java POJOs to and fr

2019-01-21 17:05发布

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.

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

标签: java xml json pojo
10条回答
男人必须洒脱
2楼-- · 2019-01-21 17:14

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.

查看更多
Viruses.
3楼-- · 2019-01-21 17:14

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.

查看更多
劫难
4楼-- · 2019-01-21 17:19

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.

查看更多
女痞
5楼-- · 2019-01-21 17:23

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.

查看更多
做个烂人
6楼-- · 2019-01-21 17:23

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.

查看更多
The star\"
7楼-- · 2019-01-21 17:24

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

查看更多
登录 后发表回答