views:

68

answers:

2

Hi, I would like to know if there is a webpage/software that can "translate" a Json feed object to a Java object with attributes.

For example :

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

Would become:

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

I'm not asking that because I'm lazy, but the JSON I would like to parse has quite a lot of attribute.

A: 

Hi,

You might want to have a look at Gson, Google's JSON Java library. It has methods to serialize objects from Java to JSON and deserialize from JSON to Java object.

I have never used it for deserialization so I can't provide much details on that, for example how it would handle the nested object (address) but I guess it's able to deal with it.

The API doc : http://google-gson.googlecode.com/svn/tags/1.3/docs/javadocs/index.html The user guide : https://sites.google.com/site/gson/gson-user-guide

Good luck !

Pierre Henry
+1  A: 

Hi,

I've successfully used json-lib for json serialization and deserialization. Your example would look like this:

String json = "{'firstName': 'John', 'lastName': 'Smith', 'address': {'streetAddress': '21 2nd Street', 'city': 'New York'}}";
JSONObject jsonObject = JSONObject.fromObject(json);
Person bean = (Person) JSONObject.toBean(jsonObject, Person.class);
System.out.println(bean);

And prints

firstName: John, lastName: Smith, address: [streetAddress: 21 2nd Street, city: New York]

If you need to customize it there are plenty of extension hooks. In my application i added support for serializing a Locale to a string "sv_SE" rather than an object. And for deserializing that same string to a Locale object.

sigget