如何将JSONArray转换为int数组?

我遇到了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 [] …

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

我从来没有使用过它,也没有测试它,但是看看你的代码和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值。 如果索引没有值,或者该值不是数字且无法转换为数字,则返回零。

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

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

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

这是一个处理JSONArray转换为Int Array的简单方法

 public static int[] JSonArray2IntArray(JSONArray jsonArray){ int[] intArray = new int[jsonArray.length()]; for (int i = 0; i < intArray.length; ++i) { intArray[i] = jsonArray.optInt(i); } return intArray; } 

你也可以这样做

 JSONArray numberArr=jsonObject.getJSONArray("numbers"); int[] arr=new int[numberArr.length()]; for(int k=0;k 

代替 –

 result.put("numbers", numbers); 

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

 result.put(numbers); 

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