tags:

views:

89

answers:

5

Does anyone know if there is the ability to generate objects for JSON data? I know there are generic JSON object libraries, but I am looking for more specific - similar to how jaxb can convert SOAP definitions or XSDs into an object model. I know there would need to be some sort of JSON definition file (which I do not know if that concept even exists within JSON), but I feel like that would be a lot more beneficial. Think:

Generic case:

genericJsonObect.get("name");

Specific case:

specificJsonObject.getName();
+1  A: 

I think the Jackson data mapper can do what you need. It can serialize/deserialize a real Java object into a Json tree.

But others API should also work :

  • Sojo
  • FlexJSON
  • Gson
Benoit Courtine
A: 

might be helpful

org.life.java
+3  A: 

Jackson and XStream have the ability to map json to POJOs.

Sasi
I would recommend Jackson
Eric W
+4  A: 

Do you want the .java source file to be generated for you? Or to map exiting java beans to JSON objects?

If the former, there is no such a library ( that I'm aware of ) if the later, Google GSON is exactly what you need.

From the samples:

class BagOfPrimitives {
    public int value1 = 1;
    private String value2 = "abc";
    private transient int value3 = 3;
    BagOfPrimitives() {
    // no-args constructor
    }
}

(Serialization)

BagOfPrimitives obj = new BagOfPrimitives();
Gson gson = new Gson();
String json = gson.toJson(obj); 
System.out.println( json );

Prints

{"value1":1,"value2":"abc"}

( Deserialization )

BagOfPrimitives obj2 = gson.fromJson(json, BagOfPrimitives.class);   
System.out.println( obj2.value1 ) ; // value1 is 1
OscarRyz
i was hoping there was a way to generate the pojo java classes based on some definition.
wuntee
That's not extremely hard to do. Actually it would be a good candidate for a small opens source project :)
OscarRyz
A: 

I am not familiar of such code generation project, although I am sure many Java JSON library projects would be interested in having such thing. Main issue is that there is good Schema language for JSON that would allow code generation; JSON Schema only works for validation.

However: one possibility you could consider is to just use JAXB to generate beans, and then use Jackson to use those beans. It has support for JAXB annotations so you would be able to work with JSON and beans generated.

StaxMan