我遇到了关于 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]}
How can I do that?
Client code:
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[]...
无论如何它都不起作用。