tags:

views:

4699

answers:

6

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?

Cheers, Darren

+2  A: 

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

Mr. Will
Did you succeed with this classes? I run some tests and get a infinite loop. I need to parse a generic JSON to XML withou Pojo.
Castanho
I actually have since used XStream which seemed to work well.
Mr. Will
+4  A: 

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.

Joachim Sauer
A: 

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.

R. Bemrose
+4  A: 

Use Xstream http://xstream.codehaus.org/ 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.

Calm Storm
Xstream supports serialization to JSON: http://xstream.codehaus.org/json-tutorial.html
Kariem
I tried Xstream but found a variety of limitations with JsonHierarchicalStreamDriver and the JettisonMappedXmlDriver.1) The Stream driver cannot deserialize it can only serialize2) The mapped xml driver can do both but cannot produce pretty JSONIf one is ok with the above constraints, XSTREAM is a good choice.
Calm Storm
A: 

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.

StaxMan
A: 

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

Jay R.