如何将JSONArray转换为int数组?

前端之家收集整理的这篇文章主要介绍了如何将JSONArray转换为int数组?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我遇到了JSONObject sayJSONHello()方法的问题.
  1. @Path("/hello")
  2. public class SimplyHello {
  3.  
  4. @GET
  5. @Produces(MediaType.APPLICATION_JSON)
  6.  
  7. public JSONObject sayJSONHello() {
  8.  
  9. JSONArray numbers = new JSONArray();
  10.  
  11. numbers.put(1);
  12. numbers.put(2);
  13. numbers.put(3);
  14. numbers.put(4);
  15.  
  16. JSONObject result = new JSONObject();
  17.  
  18. try {
  19. result.put("numbers",numbers);
  20. } catch (JSONException e) {
  21. // TODO Auto-generated catch block
  22. e.printStackTrace();
  23. }
  24.  
  25. return result;
  26. }
  27. }

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

  1. {"numbers":[1,4]}

我怎样才能做到这一点?

客户代码

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

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

我将函数视为JSONObject.

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

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

另外两种方式

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

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

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

我从来没有使用过它,也没有测试过它,但是查看你的代码JSONObjectJSONArray的文档,这就是我的建议.
  1. // Receive JSON from server and parse it.
  2. String jsonString = service.path("rest").path("hello")
  3. .accept(MediaType.APPLICATION_JSON).get(String.class);
  4. JSONObject obj = new JSONObject(jsonString);
  5.  
  6. // Retrieve number array from JSON object.
  7. JSONArray array = obj.optJSONArray("numbers");
  8.  
  9. // Deal with the case of a non-array value.
  10. if (array == null) { /*...*/ }
  11.  
  12. // Create an int array to accomodate the numbers.
  13. int[] numbers = new int[array.length()];
  14.  
  15. // Extract numbers from JSON array.
  16. for (int i = 0; i < array.length(); ++i) {
  17. numbers[i] = array.optInt(i);
  18. }

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

Get the optional int value associated with an index. Zero is returned if there is no value for the index,or if the value is not a number and cannot be converted to a number.

猜你在找的Json相关文章