aspose file tools*
The moose likes Web Services and the fly likes Deserialize JSON to Java class Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Web Services
Bookmark "Deserialize JSON to Java class" Watch "Deserialize JSON to Java class" New topic
Author

Deserialize JSON to Java class

James Dekker
Ranch Hand

Joined: Dec 09, 2006
Posts: 215
Lets say that I have a json object that looks like this:



Is there a way to unmarshall this JSON object to autogenerated Java class (or does the classes already have to be defined)?

Would the classes look like this:







Question(s):

(1) Do I need to have these objects in place or can the Jackson library deserialize this for me and produce the Java source classes?

(2) Are my classes conducive to the JSON Object that I listed above?

With thanks!
Bear Bibeault
Author and ninkuma
Marshal

Joined: Jan 10, 2002
Posts: 61437
    
  67

I believe that the class must already exist -- at least for libraries such as Gson (I think Jackson is similar, though I haven't used it much). You can get Gson to create a Map structure that represents the JSON, but it won't magically create a new class definition and load it.

If it's a known construct, why not create a class to represent it? Or is it completely random?


[Asking smart questions] [Bear's FrontMan] [About Bear] [Books by Bear]
James Dekker
Ranch Hand

Joined: Dec 09, 2006
Posts: 215
Thanks Bear!

The reason is because the JSON has been created theoretically by a non programmer (everyone loves DSL programming ).

And I don't know if this JSON object would deserialize it into one large class or does this class need separate inner classes.

How would one design their prospective Java classe(s) to support this particular JSON object design?
Bear Bibeault
Author and ninkuma
Marshal

Joined: Jan 10, 2002
Posts: 61437
    
  67

Nested objects are usually their own class. They do not need to be inner classes.

I would design in the other direction though: define the Java classes first, to model what they need to model, and the JSON falls naturally out of that.
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: Deserialize JSON to Java class