使用gson为多个记录的JSON到java对象

时间:2015-03-31 18:50:01

标签: java json

I have my json file and corresponding java bean classes.
JSON file has multiple records,So i have LIST of objects,where i am facing the problem.LIST is not being populated. 
JSON file:
{"RequestServices":
{`enter code here`
"RequestService":
[
{
"orderNumber":456,
"organizationId":123,
"headerId":3446
}
]
}
}
JAVA CLASSES:
public class RequestServices {
    private List<RequestService> requestServices=new ArrayList<RequestService>();//array of objects     
//default getter,setter of List<RequestService>
}
-----
public class RequestService {   
    private String orderNumber;
    private String organizationId;
    private String headerId;
    /* setters and getters */}
-----
Main.class
public class JSONBind {
    public static void main(String[] args) {
    Gson gson = new Gson();
    try {
        BufferedReader br = new BufferedReader(new fileReader("c:\\JSON1.json"));
        //convert the json string back to object
        RequestServices obj = gson.fromJson(br, RequestServices.class);

System.out.println(obj.getRequestServices()。get(0).getOrderNumber()); //获取错误         }}}     当我尝试打印对象列表(即REquestService)时,它给出了IndexOutofBound     在此先感谢,Waitin的帮助!

1 个答案:

答案 0 :(得分:0)

我注意到你的json中有以下层次结构

RequestServices -> RequestService[]

但是在你的Pojos中你有RequestServices -> requestServices尝试重命名你的pojo或你的json以匹配属性requestServices

或者您可以使用注释@SerializedName("requestServices")

映射POJO中的字段

有关完整文档,您可以查看网站:Gson Doc

希望它有所帮助!