This week's book giveaway is in the OO, Patterns, UML and Refactoring forum.
We're giving away four copies of Refactoring for Software Design Smells: Managing Technical Debt and have Girish Suryanarayana, Ganesh Samarthyam & Tushar Sharma on-line!
See this thread for details.
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: 221
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: 63202
    
  69

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: 221
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: 63202
    
  69

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.
 
I’ve looked at a lot of different solutions, and in my humble opinion Aspose is the way to go. Here’s the link: http://aspose.com
 
subject: Deserialize JSON to Java class
 
It's not a secret anymore!