Generate JSON sample from POJO Generate JSON sample from POJO json json

Generate JSON sample from POJO


There is also another library called Genson http://code.google.com/p/genson/.

Actually Genson is faster and has more features than Gson and has performances close to jackson (but its a lot more lightweight) see http://code.google.com/p/genson/wiki/Metrics. It uses à streaming api instead of a dom model that brings better scalability and is nice in web applications where you can handle the conversion as the input arrives.

Genson is well suited for all kind of use cases, ranging from simple conversion, to full customization of all the process. You can configure a lot of things (use fields and/or methods, use constructor with arguments and without any annotation, filter properties by visibility and a lot more). You should have a look at the wiki.

Its latest version (0.91) is avaible in maven central repository.

<dependency>    <groupId>com.owlike</groupId>    <artifactId>genson</artifactId>    <version>0.91</version></dependency>

Disclaimer: I'm the author of the library but I try to be objective (especially in the benchmarks).

EditA few words on Gson and Jackson. I have used Jackson for more than 2 years and a bit Gson. First thing to note is that Jackson is the fastest json/java library out there (Gesnon tries to beat it but its quite hard). Jackson has also a lot of features and configuration possibilities (most based on annotations). I had standard and advanced use of Jackson, and it was nice until I needed features that Jackson didn't provide. I found that the library was real hard to extend (for my use cases it was impossible without rewriting a big part).

I then tried Gson. First thing to note about Gson is that it does not use getter/setter but only fields! Its performances were not good (especially compared to Jackson or Genson).With the latest versions it has improved as they also provide a streaming api, but its still not fast enough. At the begining its main advantage was good support of Java generics but Jackson and Genson provide it too. Note also that Gson comes with less features out of the box than Genson or Jackson.I also tried to implement the features I needed in Gson but I found that the Beans databinding part was not extensible (near everything in a single class with no extension points), so I would have to rewrite it. It was out of question and thats how I ended up with creating Genson.

If you don't want to use Genson, I really recommend you Jackson over Gson.


You might also take a look at Gson (it directly reads/writes fields, no need for getters/setters):

Foo foo = ...Gson gson = new Gson();String json = gson.toJson(foo);

Do yourself a favor and don't hand-code JSON (or XML, or any structured data format if you can avoid it). It's unnecessarily reinventing the wheel. Someone has done it before and already solved escaping, nesting and all kinds of border cases for you.