Search code examples
jsongwtautobean

GWT Autobean - how to handle lists?


I have been trying to evaluate GWT Autobean feature to decode/encode JSON object to domain objects for REST calls.

Following the example : http://code.google.com/p/google-web-toolkit/wiki/AutoBean#Quickstart

I was able to convert a singular JSON object to a domain object:

AutoBean<Person> personBean = AutoBeanCodex.decode(factory, Person.class, JsonResources.INSTANCE.json().getText());

where JsonResources.INSTANCE.json() is returning a JSON string.

However, I haven't been successful to convert a list of Person objects from JSON.

It would be helpful, if anyone has an example of this?

Thanks!


Solution

  • Well the only way I can think of is to create a special autobean, which will have List<Person> property. For example:

    public interface Result {
        void setPersons(List<Person> persons);
        List<Person> getPersons();
    }
    

    And example json string:

    {
       persons:[
          {"name":"Thomas Broyer"},
          {"name":"Colin Alworth"}
       ]
    }
    

    UPDATE: Workaround when input JSON is an array ( as suggested by persons[0] in comments).E.g. JSON looks like this:

    [{"name":"Thomas Broyer"},{"name":"Colin Alworth"}]
    

    And parsing code looks like this:

    AutoBeanCodex.decode(factory, Result.class, "{\"persons\": " + json + "}").getPersons();