简体   繁体   中英

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?

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()) {
    ...
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM