问题
I need an open-source tool which can convert POJOs to XML and JSON strings.
Jersey (and probably other JAX-RS implementations) would fit these requirements if mappings could be configured through xml-files but not through annotations.
Is there anything suitable?
回答1:
POJO to XML
JAXB is the Java standard (JSR-222) for converting Java objects to/from XML (I am a member of the JAXB expert group):
- http://bdoughan.blogspot.com/2010/07/jaxb-xml-binding-standard.html
POJO to JSON
People have been using JAXB with Jettison to produce JSON. This is how Jersey (JAX-RS reference implementation) converts POJOs to JSON by default.
- http://bdoughan.blogspot.com/2011/04/jaxb-and-json-via-jettison.html
XML Configuration
If you require the ability to configure the metadata via XML, then you can use EclipseLink JAXB (MOXy), I'm the MOXy tech lead:
- http://bdoughan.blogspot.com/2010/12/extending-jaxb-representing-annotations.html
回答2:
There are lots of suitable JSON libraries; aside from GSON that was mentioned, Jackson is an obvious choice. Typically you don't need any annotations; but even if you neded, Jackson can use so-called mix-in annotations which means associating configuration, not modifying actual POJOs. Finally, Jackson supports JAXB annotations if you must use them (for example, when using JAXB for producing XML).
And as an added bonus, there is Jackson extension module, jackson-xml-databind, which can data bind POJOs to and from XML, so you can just use one library for both.
回答3:
Have you tried Castor?
http://www.castor.org/
Supports XML mapping -
http://www.castor.org/xml-mapping.html
From XML, you could use json-lib if you need JSON.
http://answers.oreilly.com/topic/278-how-to-convert-xml-to-json-in-java/
回答4:
Check out GSON for converting POJOs to JSON:
http://code.google.com/p/google-gson/
We've been using for a couple of years now. Very excellent library.
For POJOs to XML, Jersey uses JAXB or you could roll your own serializer.
来源:https://stackoverflow.com/questions/5195649/a-tool-for-transforming-pojo-to-xml-and-json-based-on-xml-mapping-is-needed