简体   繁体   中英

Generate JSON sample from POJO

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.

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.

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

Using GSON :

Foo foo = new Foo();
foo.setVar1("string1");
foo.setVar2("string2");

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

Note: I'm the EclipseLink JAXB (MOXy) lead and a member of the JAXB (JSR-222) expert group.

You can use EclipseLink JAXB (MOXy) to convert your object model to JSON (and/or XML). Below is a complete example.

jaxb.properties

To specify MOXy as your JAXB provider you need to include a file called jaxb.properties in the same package as your domain model with the following entry (see: http://blog.bdoughan.com/2011/05/specifying-eclipselink-moxy-as-your.html ).

javax.xml.bind.context.factory=org.eclipse.persistence.jaxb.JAXBContextFactory

Demo

The demo code below can be used to produce the JSON output from an instance of foo . Note how only the standard JAXB APIs are used. The JAXB APIs have been in the JDK/RE since Java SE 6.

package forum12101023;

import javax.xml.bind.*;

public class Demo {

    public static void main(String[] args) throws Exception {
        JAXBContext jc = JAXBContext.newInstance(foo.class);

        foo foo = new foo();
        foo.setVar1("string1");
        foo.setVar2("string2");

        Marshaller marshaller = jc.createMarshaller();
        marshaller.setProperty("eclipselink.media-type", "application/json");
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        marshaller.marshal(foo, System.out);
    }

}

Output

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

For More Information

You can use Gson to do it.

Gson gson = new Gson();   
String fooJSON= gson.toJson(foo);  

Check this link for a detail explanation also how to do it in JS/Extjs and also deserializing from JSON to POJO

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM