2014-10-06 69 views
0

我有一個JSON,我想使用Autobean解析。我得到的NullPointerException在for循環中,可能persons.getPersons()使用Autobean解析JSON數組

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

我AppAutoBeanFactory看起來是這樣的:

interface AppAutoBeanFactory extends AutoBeanFactory { 

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


} 

的JSON(可變strResponse)看起來是這樣的:

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

我製作了這些接口:

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); 
} 

我該如何讓它工作?以及如何將記錄數組添加到IPerson?

回答

0

你做它的方式,你期待的JSON有{"persons:{"persons":[…]}}:外部對象是一個PersonsWrapperpersons屬性是IPersons,其persons屬性是List<IPerson>

嘗試開溝PersonsWrapper,只是使用IPersons代替:

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

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