Alex Rivera | Logout

Generate JSON sample from POJO

Asked 2012-08-23T22:42:42.313
11

We are looking for a way (maybe existing framework or similar) to generate sample JSON fragments based on POJOs (source or binary). For example:

public class foo {
   String var1;
   String var2;

   public String getVar1() { return var1; }
   public void setVar1(String var1) { this.var1 = var1; }

   public String getVar2() { return var2; }
   public void setVar2(String var2) { this.var2 = var2; }
}

would yield a JSON sample that could look like:

{
  "var1": "string1",
  "var2": "string2"
}

any ideas? We could of course hand code that. Just looking to see if there is something already out there.

Edit
Report

1 Answer

4

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

Edit A 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

answered 2012-08-24T10:11:12.133

Your Answer