我遇到了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,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 [] …
它无论如何都不起作用..
我从来没有使用过它,也没有测试过它,但是查看你的代码和
JSONObject
和
JSONArray
的文档,这就是我的建议.
- // 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,或者不是整数.
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.