How to cast JSONArray to int array?

后端 未结 5 1541
一生所求
一生所求 2020-12-06 18:31

I\'m having problems with the method JSONObject sayJSONHello().

@Path(\"/hello\")
public class SimplyHello {

    @GET
    @Produces(MediaType.A         


        
5条回答
  •  自闭症患者
    2020-12-06 18:50

    I've never used this, nor have I tested it, but looking at your code and the documentation for JSONObject and JSONArray, this is what I suggest.

    // 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);
    }
    

    This should work for your case. On a more serious application, you may want to check if the values are indeed integers, as optInt returns 0 when the value does not exist, or isn't an integer.

    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.

提交回复
热议问题