I\'m having problems with the method JSONObject sayJSONHello()
.
@Path(\"/hello\")
public class SimplyHello {
@GET
@Produces(MediaType.A
You can also do this
JSONArray numberArr=jsonObject.getJSONArray("numbers");
int[] arr=new int[numberArr.length()];
for(int k=0;k<numberArr.length();k++)
arr[k]=numberArr.getInt(k);
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.
Here is a simple method that handles JSONArray
converting to Int Array
:
public static int[] JSonArray2IntArray(JSONArray jsonArray){
int[] intArray = new int[jsonArray.length()];
for (int i = 0; i < intArray.length; ++i) {
intArray[i] = jsonArray.optInt(i);
}
return intArray;
}
Instead of -
result.put("numbers", numbers);
you can try (I haven't tested this though)
result.put(numbers);
Or iterate through the array "numbers" and put each one individually into the "result".
If you can accept a List as a result, and also can accept using Gson, there is a pretty easy way of doing this, in just a few lines of code:
Type listType = new TypeToken<LinkedList<Integer>>() {}.getType();
List<Integer> numbers = new Gson().fromJson(jobj.get("numbers"), listType);
I realize this is not exactly what you are asking for, but in my experience, a list of integers can be used in many of the same ways as a basic int[]. Further info on how to convert a linkedlist to an array, can be found here: How to convert linkedlist to array using `toArray()`?