tags:

views:

1051

answers:

4

Hi. I want utility that generates classes from JSON. For example we got

"firstName": "John",  
"lastName": "Smith",  
"address": {  
  "streetAddress": "21 2nd Street",  
   "city": "New York"
}

We pass this to our util and on exit we have 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.

+2  A: 

There are some good answers here:

http://stackoverflow.com/questions/658936/is-there-a-library-to-convert-java-pojos-to-and-from-json-and-xml

EDIT: from this link:

http://jackson.codehaus.org/Tutorial

you have an example using the ObjectMapper():

ObjectMapper mapper = new ObjectMapper(); // can reuse, share globally
User user = mapper.readValue(new File("user.json"), User.class);

i.e. you have to have your java class/POJO already defined, but once it is you can create an instance of this class very quickly.

davek
Didn't find answer.Please point me.
Orsol
I've added a bit extra in my answer.
davek
I asked for tool that generates definition for classes.
Orsol
I've looked for just such a thing and couldn't find anything. In retrospect I decided it wasn't such a good idea anyway (for my situation, at least).
davek
+4  A: 

I recommend using Google Gson for this. It really eases converting JSON to fullworthy Javabeans and it has also excellent support for generics.

Here's a basic example which can be used for your JSON string:

package test;

import com.google.gson.Gson;

public class Test {

    public static void main(String... args) throws Exception {
        String json = 
            "{"
                + "'firstName': 'John',"
                + "'lastName': 'Smith',"
                + "'address': {"
                    + "'streetAddress': '21 2nd Street',"
                    + "'city': 'New York'"
                + "}"
            + "}";

        // Now do the magic.
        Person person = new Gson().fromJson(json, Person.class);

        // Show it.
        System.out.println(person); // firstName: John, lastName: Smith, address: [streetAddress: 21 2nd Street, city: New York]
    }

}

class Person {
    private String firstName;
    private String lastName;
    private Address address;

    public String getFirstName() { return firstName; }
    public String getLastName() { return lastName; }
    public Address getAddress() { return address; }

    public void setFirstName(String firstName) { this.firstName = firstName; }
    public void setLastName(String lastName) { this.lastName = lastName; }
    public void setAddress(Address address) { this.address = address; }

    public String toString() {
        return String.format("firstName: %s, lastName: %s, address: [%s]", firstName, lastName, address);
    }
}

class Address {
    private String streetAddress;
    private String city;

    public String getStreetAddress() { return streetAddress; }
    public String getCity() { return city; }

    public void setStreetAddress(String streetAddress) { this.streetAddress = streetAddress; }
    public void setCity(String city) { this.city = city; }

    public String toString() {
        return String.format("streetAddress: %s, city: %s", streetAddress, city);
    }
}

For another example also see this answer.

BalusC
My point is to find tool that generates class definition from JSON
Orsol
You want to generate classes runtime? How would you **use** it further without knowing what methods you should access? Better map it to a `Map<String, Object>`.
BalusC
Not in runtime .
Orsol
Thus, you want reverse engineer Java classes from a bunch of JSON structures before use? Something like Hibernate can do based on SQL CREATE and/or XML? No one comes directly to mind, but there may be tools to convert JSON to XML and there are also tools to reverse engineer beans based on XML.
BalusC
You understand me right.Thanks for advice with xml, but it to complicate.
Orsol
WOuld it be possible to nest the Address class inside the Person class? If so, could someone should me an example?
Mridang Agarwalla
@mridang: It is already nested.
BalusC
I meant nesting the class declaration itself.
Mridang Agarwalla
Sure you can. This is not related to Gson. This is related to basic Java. I suggest to get yourself through some basic Java tutorials over there at sun.com. Check [Trails covering the basics](http://java.sun.com/docs/books/tutorial/). If you stucks, just press `Ask Question` button at right top.
BalusC
A: 

Thanks all who attempted to help.
For me this script was helpful. It process only flat JSON and don't take care of types, but automate some routine

  String str = 
        "{"
            + "'title': 'Computing and Information systems',"
            + "'id' : 1,"
            + "'children' : 'true',"
            + "'groups' : [{"
                + "'title' : 'Level one CIS',"
                + "'id' : 2,"
                + "'children' : 'true',"
                + "'groups' : [{"
                    + "'title' : 'Intro To Computing and Internet',"
                    + "'id' : 3,"
                    + "'children': 'false',"
                    + "'groups':[]"
                + "}]" 
            + "}]"
        + "}";



    JSONObject json = new JSONObject(str);
    Iterator<String> iterator =  json.keys();

    System.out.println("Fields:");
    while (iterator.hasNext() ){
       System.out.println(String.format("public String %s;", iterator.next()));
    }

    System.out.println("public void Parse (String str){");
    System.out.println("JSONObject json = new JSONObject(str);");

    iterator  = json.keys();
    while (iterator.hasNext() ){
       String key = iterator.next();
       System.out.println(String.format("this.%s = json.getString(\"%s\");",key,key ));

    System.out.println("}");
Orsol
A: 

As far as I know there is no such tool. Yet.

The main reason is, I suspect, that unlike with XML (which has XML Schema, and then tools like 'xjc' to do what you ask, between XML and POJO definitions), there is no fully features schema language. There is JSON Schema, but it has very little support for actual type definitions (focuses on JSON structures), so it would be tricky to generate Java classes. But probably still possible, esp. if some naming conventions were defined and used to support generation.

However: this is something that has been fairly frequently requested (on mailing lists of JSON tool projects I follow), so I think that someone will write such a tool in near future.

So I don't think it is a bad idea per se (also: it is not a good idea for all use cases, depends on what you want to do ).

StaxMan