2016-03-21 166 views
-1

我有一個具有整數和字符串值的多維數組。我想以json格式轉換數組並將其發送回ajax函數。我試圖打印數組內容來檢查,但我無法這樣做。將數組轉換爲json

Os[] o1 = new os[]; 
o1[0].os_name = "xyz"; 
o1[0].os_id = 1; 
JSONArray jsArray = new JSONArray(o1); 

for (int i = 0; i < jsArray.length(); ++i) { 
    JSONObject rec = jsArray.getJSONObject(i); 
    int id = rec.getInt("os_id"); 
    String loc = rec.getString("os_name"); 
    System.out.println(id+loc); 
} 

我有一個OS分類:

public class Os { 

    int os_id; 
    String os_name; 

} 

我得到一個錯誤:

JSONObject["os_id"] not found.

+2

當使陣列將幫助,也許就像聲明大小: '輸出[] 01 =新的Os [1];' –

+2

您的第一行已損壞。 Os [] o1 = new os [];第二個'os'不是指一個對象,並且該數組沒有被聲明爲一個大小。 – Creperum

+3

'o1 [0] .os_name =「xyz」;'不應該工作,因爲1)您的數組沒有大小。並且2)數組中沒有對象 –

回答

0

所有你需要首先初始化數組對象你正在使用。 其次,你需要提供評估(gettters)爲JSON API使用的O的對象屬性的工作

你的主要問題的關注,缺乏干將在bean。要解決此問題,請更改OS分類是這樣的:

public class Os { 

    int os_id; 
    String os_name; 

    public int getOs_id() { 
     return os_id; 
    } 

    public String getOs_name() { 
     return os_name; 
    } 

} 

然後你的更正後的代碼將是:

// In Java the Arrays must have a size 
Os[] o1 = new Os[1]; 

/* The Array contains only null values by default. You must create 
    objects and assign them to the newly created Array. 
    (In your example, only one object is created) */ 

Os anOs = new Os(); 
anOs.os_name = "xyz"; 
anOs.os_id = 1; 

// Assign the object to the Array index 0 
o1[0]=anOs; 

JSONArray jsArray = new JSONArray(o1); 

for (int i = 0; i < jsArray.length(); ++i) { 
    JSONObject rec = jsArray.getJSONObject(i); 
    int id = rec.getInt("os_id"); 
    String loc = rec.getString("os_name"); 
    System.out.println(id+loc); 
} 
+0

您實際上只需要獲取它的吸氣工具 –

+0

@ cricket_007所提供的示例功能不全,因此我對其進行了更正。你是對的,主要問題與強制getter/setter有關,Json API能夠按預期工作。 –

+1

我只是指這樣一個事實,即制定者不需要,只是獲得者。你可以看到我的答案供參考。 –

0

假設你的意思做這個

Os[] osArray = new Os[1]; 
Os os1 = new Os(); 
os1.os_id = 1; 
os1.os_name = "xyz"; 
osArray[0] = os1; 

JSONArray jsonArray = new JSONArray(osArray); 

I am trying to print the array contents

您可以做到這一點

System.out.println(jsonArray.toString()); 

這將在數組內打印一個空的JSON對象。

[{}] 

因此,您的錯誤是有道理的,因爲您有一個沒有鍵的空對象。

爲了解決這個問題,更新您的類像這樣

public class Os { 
    int os_id; 
    String os_name; 

    public int getOs_id() { 
     return os_id; 
    } 

    public String getOs_name() { 
     return os_name; 
    } 
} 

,您現在會看到

[{"os_id":1,"os_name":"xyz"}]