Search code examples
javajsongwtautobean

Parsing JSON array using Autobean


I have a JSON which I'd like to parse using Autobean. I'm getting NullPointerException in the for loop, probably persons.getPersons()

AppAutoBeanFactory factory = GWT.create(AppAutoBeanFactory.class);
    AutoBean<PersonsWrapper> bean =AutoBeanCodex.decode(factory, PersonsWrapper.class, "{\"persons\": " + strResponse + "}");
    IPersons persons = bean.as().getPersons();


        for (IPerson person : persons.getPersons()) {
            ...
        }

my AppAutoBeanFactory looks like this:

 interface AppAutoBeanFactory extends AutoBeanFactory {

   AutoBean<IPerson> person();
   AutoBean<IPersons> ipersons();
   AutoBean<PersonsWrapper> persons();


}

The JSON (variable strResponse) looks like this:

[
  {
    "name":"John",
    "surname":"Blue",
    "records":[10.5, 12.5, 18.6]
  },
  {
    "name":"Steven",
    "surname":"Green",
    "records":[11.5, 15.5, 14.6]
   }
]

I've made these interfaces:

public interface PersonsWrapper {
 IPersons getPersons();
}

public interface IPersons {

    void setPersons(List<IPerson> persons);
    List<IPerson> getPersons();

}

public interface IPerson {

  String getName();
  void setName(String name); 
  String getSurname();
  void setSurname(String surname);
}

How can I make it work? And how to add the records array to IPerson?


Solution

  • The way you did it, you're expecting the JSON to have {"persons:{"persons":[…]}}: the outer object is a PersonsWrapper whose persons property is a IPersons, whose persons property is a List<IPerson>.

    Try ditching PersonsWrapper and just using IPersons instead:

    IPersons bean =AutoBeanCodex.decode(factory, IPersons.class, "{\"persons\": " + strResponse + "}").as();
    
    for (IPerson person : bean.getPersons()) {
        ...
    }