2016-03-21 189 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"}]