0

Is it possible to parse a JSON message using GWT AutoBeans when one of the objects returned may be a collection but not always?

For example, if I have a JSON message returning an author and his/her associated writings, it's possible that there could be zero or more books being returned.

{ "name" : "William Gibson", "books" : { bookname : "Neuromancer" } }

could be one response, but so could this:

{ "name" : "William Gibson", "books" : [ { bookname: "Neuromancer"}, { bookname : "Pattern Recognition" } ] }

When I attempt to model this with an interface to be used for marshalling with an AutoBean, I get "expecting indexed data" errors if only one book is returned.

Interface for the AutoBean:

public interface Author {
  @PropertyName(value="name")
  String getAuthorName();
  @PropertyName(value="book")
  List<String> getBooks();
}

Snippet of error:

java.lang.AssertionError: Expecting indexed data
at com.google.web.bindery.autobean.shared.impl.SplittableList.<init>(SplittableList.java:64)

Is this not possible with AutoBeans?

(Note: using GWT 2.5.0 GA)

Bionic_Geek
  • 536
  • 4
  • 24

1 Answers1

1

If you have a List, AutoBeans expects a JSON array. That array could contain zero, one or more elements, but it has to be an array (or be absent).

I think you can make your getBooks method return a Splittable though. You could then know whether it's an array (isIndexed()) or not. If you need the array to contain objects, you'd then have to iterate on the array (size() and get(int)) and pass each element to AutoBeanCodex.decode() to decode them (or directly pass the splittable if it's not an array).

Thomas Broyer
  • 64,353
  • 7
  • 91
  • 164
  • Ok but if I have no control over the JSON message itself (e.g. I cannot force it into an array format of n elements), is there no way to model the AutoBean in a way that it can handle when only one element is returned? – Bionic_Geek Nov 28 '12 at 15:13
  • I think you could use a `Splittable` property type; see edited answer. – Thomas Broyer Nov 28 '12 at 15:23