2

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();

5 Answers 5

3

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

Sign up to request clarification or add additional context in comments.

Comments

3

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

2 Comments

i was hoping there was a way to generate the pojo java classes based on some definition.
That's not extremely hard to do. Actually it would be a good candidate for a small opens source project :)
1

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

Comments

0

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.

Comments

0

I have found this site very useful.

http://jsongen.byingtondesign.com/ and have used it in our projects.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.