2015-03-31 50 views
-3
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()得到(0).getOrderNumber()); //獲取錯誤 }}} 當我嘗試打印對象列表(即REquestService),它給出IndexOutofBound 在此先感謝,Waitin爲您提供幫助!JSON到Java對象使用GSON多個記錄

回答

0

我在你的JSON注意到你有以下層次

RequestServices -> RequestService[] 

但在你的POJO你RequestServices -> requestServices嘗試重命名你的POJO,或者你的JSON的性能匹配requestServices

或者你可以映射POJO中的註釋字段@SerializedName("requestServices")

要獲取完整文檔,您可以查看網站:Gson Doc

希望它有幫助!

+0

非常感謝,我將變量名改爲與json文件完全相同,現在它的工作正常, – user1570345 2015-04-01 05:00:43

+0

但是,我們可以將json值映射到GSON中的java對象變量名嗎? – user1570345 2015-04-01 05:01:28

+0

很高興爲您服務!當它解決了問題時,你可以請,接受答案?關於你的問題我不明白,你能解釋一下嗎? – 2015-04-01 05:03:11