0 votes
1 view
in Java by (8.5k points)

I want a utility that generates java source files from JSON. For example we have

{

  "firstName": "John",  

  "lastName": "Smith",  

  "address": {  

    "streetAddress": "21 2nd Street",  

     "city": "New York"

  }

}

We pass this to the utility and we want it to generate something like this:

class Address  {

    JSONObject mInternalJSONObject;

    Address (JSONObject json){

        mInternalJSONObject = json;

    }

    String  getStreetAddress () {

        return mInternalJSONObject.getString("streetAddress");

    }

    String  getCity (){

        return mInternalJSONObject.getString("city");

    }

}

class Person {        

    JSONObject mInternalJSONObject;

    Person (JSONObject json){

        mInternalJSONObject = json;

    }

    String  getFirstName () {

        return mInternalJSONObject.getString("firstName");

    }

    String  getLastName (){

        return mInternalJSONObject.getString("lastName");

    }

    Address getAddress (){

        return Address(mInternalJSONObject.getString("address"));

    }

}

Not so hard to write, but I'm sure somebody already did it.

1 Answer

0 votes
by (42.1k points)

Try:

http://www.jsonschema2pojo.org

Orsol, I'm sure you're not still waiting for an solution here, but for the sake of the next person that finds this thread I thought I'd add some more info.

Two things have happened since Dec '09 when this question was asked:

  • The JSON Schema spec has moved on a lot. It's still in draft (not finalised) but it's close to completion and is now a viable tool specifying your structural rules
  • I've recently started a new open source project specifically intended to solve your problem: jsonschema2pojo. The jsonschema2pojo tool takes a json schema document and generates DTO-style Java classes (in the form of .java source files). The project is not yet mature but already provides coverage of the most useful parts of json schema. I'm looking for more feedback from users to help drive the development. Right now you can use the tool from the command line or as a Maven plugin.

Hope this helps!

Welcome to Intellipaat Community. Get your technical queries answered by top developers !


Categories

...