加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

如何将JSONArray转换为int数组?

发布时间:2020-12-16 19:47:34 所属栏目:百科 来源:网络整理
导读:我遇到了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); numbe
我遇到了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 [] …

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

我从来没有使用过它,也没有测试过它,但是查看你的代码和 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,或者不是整数.

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.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读