如何将JSONArray转换为int数组?

时间:2013-11-19 10:20:14

标签: java json

我遇到方法JSONObject sayJSONHello()的问题。

@Path("/hello")
public class SimplyHello {

    @GET
    @Produces(MediaType.APPLICATION_JSON)

     public JSONObject sayJSONHello() {      

        JSONArray numbers = new JSONArray();

        numbers.put(1);
        numbers.put(2);
        numbers.put(3);
        numbers.put(4);             

        JSONObject result = new JSONObject();

        try {
            result.put("numbers", numbers);
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return result;
    }
}

在客户端,我想获得一个int数组,[1, 2, 3, 4],而不是JSON

{"numbers":[1,2,3,4]}

我该怎么做?

客户代码:

System.out.println(service.path("rest").path("hello")
    .accept(MediaType.APPLICATION_JSON).get(String.class));

我的方法返回JSONObject,但我想从中提取数字,以便使用这些进行计算(例如int[])。


我将函数视为JSONObject。

 String y = service.path("rest").path("hello").accept(MediaType.APPLICATION_JSON).get(String.class);   
JSONObject jobj = new JSONObject(y);   
int [] id = new int[50];
 id = (int [] ) jobj.optJSONObject("numbers:"); 

然后我得到错误:无法从JSONObject强制转换为int []

另外两种方式

String y = service.path("rest").path("hello").accept(MediaType.APPLICATION_JSON).get(String.class);   
JSONArray obj = new JSONArray(y);  
int [] id = new int[50];      
 id = (int [] ) obj.optJSONArray(0);                                                     

这次我得到:无法从JSONArray转换为int [] ...

无论如何它都不起作用..

5 个答案:

答案 0 :(得分:14)

我从来没有使用过这个版本,也没有对其进行过测试,但是查看代码和JSONObjectJSONArray的文档,这就是我的建议。

// Receive JSON from server and parse it.
String jsonString = service.path("rest").path("hello")
    .accept(MediaType.APPLICATION_JSON).get(String.class);
JSONObject obj = new JSONObject(jsonString);

// Retrieve number array from JSON object.
JSONArray array = obj.optJSONArray("numbers");

// Deal with the case of a non-array value.
if (array == null) { /*...*/ }

// Create an int array to accomodate the numbers.
int[] numbers = new int[array.length()];

// Extract numbers from JSON array.
for (int i = 0; i < array.length(); ++i) {
    numbers[i] = array.optInt(i);
}

这适用于您的情况。在更严重的应用程序中,您可能想要检查值是否确实是整数,因为optInt在值不存在时返回0,或者不是整数。

  

获取与索引关联的可选int值。如果索引没有值,或者该值不是数字且无法转换为数字,则返回零。

答案 1 :(得分:2)

如果您可以接受List作为结果,并且也可以接受使用Gson,那么只需几行代码就可以轻松实现此目的:

Type listType = new TypeToken<LinkedList<Integer>>() {}.getType();
List<Integer> numbers = new Gson().fromJson(jobj.get("numbers"), listType);

我意识到这并不是你所要求的,但根据我的经验,整数列表可以以与基本int []相同的方式使用。有关如何将链表转换为数组的更多信息,请访问:How to convert linkedlist to array using `toArray()`?

答案 2 :(得分:0)

以下是一个简单的方法,用于处理转换为JSONArray的{​​{1}}:

Int Array

答案 3 :(得分:-1)

你也可以这样做

JSONArray numberArr=jsonObject.getJSONArray("numbers");

            int[] arr=new int[numberArr.length()];
            for(int k=0;k<numberArr.length();k++)
                 arr[k]=numberArr.getInt(k);

答案 4 :(得分:-2)

而不是 -

result.put("numbers", numbers);

你可以尝试(虽然我没有测试过)

result.put(numbers);

或者遍历数组“数字”并将每个数字单独放入“结果”中。