7

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!

ankurvsoni
  • 2,064
  • 3
  • 18
  • 22

1 Answers1

18

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();
jusio
  • 9,850
  • 1
  • 42
  • 57
  • 3
    And to workaround the issue without changing the JSON: `AutoBeanCodex.decode(factory, Result.class; "{\"persons\": " + json + "}").getPersons()` – Thomas Broyer Nov 30 '12 at 19:40
  • This is the technique I use in my autobeans. But I think I'll be applying the technique made by @ThomasBroyer. – Jonathan Nov 30 '12 at 21:58
  • @ThomasBroyer good idea, I've added it to the answer since there is a little typo in your code. – jusio Dec 01 '12 at 00:08
  • Thanks for your answers. The thing is that I have a bunch of interfaces. I don't want to do this for each one of them or every time I add a new one. Is there a way to do this generically? Any ideas? – ankurvsoni Dec 05 '12 at 00:30