GWT Autobean - how to handle lists?
Asked Answered
U

1

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!

Unni answered 30/11, 2012 at 18:35 Comment(0)
P
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();
Panettone answered 30/11, 2012 at 19:19 Comment(4)
And to workaround the issue without changing the JSON: AutoBeanCodex.decode(factory, Result.class; "{\"persons\": " + json + "}").getPersons()Coiffure
This is the technique I use in my autobeans. But I think I'll be applying the technique made by @ThomasBroyer.Loella
@ThomasBroyer good idea, I've added it to the answer since there is a little typo in your code.Panettone
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?Unni

© 2022 - 2024 — McMap. All rights reserved.