11

I'm having problems with the method 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;
    }
}

In the client side, I want to get an int array, [1, 2, 3, 4], instead of the 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));

My method returns a JSONObject, but I want to extract the numbers from it, in order to perform calculations with these (e.g as an int[]).


I reveive function as a 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:"); 

And then i get error: Cannot cast from JSONObject to int[]

2 other way

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

And this time i get: Cannot cast from JSONArray to int[]...

It doesn't work anyway..

Brad Larson
  • 170,088
  • 45
  • 397
  • 571
volly
  • 147
  • 1
  • 1
  • 8
  • 2
    You can parse the json on the client side and get the number from the JSONArray right? How difficult would that be? – Rahul Nov 19 '13 at 10:23
  • 1
    As @benzonico said, you can just access the JSON object's "numbers" element and gain access to the array – Noam Rathaus Nov 19 '13 at 10:23
  • Do you really think what you expect is different from what it is returning? If yes, then please type in the JSON object you are expecting :) – dharam Nov 19 '13 at 18:27

5 Answers5

18

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.

afsantos
  • 5,178
  • 4
  • 30
  • 54
  • By the way, is any way to send numbers noit using numbers.put(1); .. ? e.g in loop ? will send 500 numbers.. – volly Nov 20 '13 at 09:05
  • @volly Do not forget to accept an answer, if any solved your problem. There sure are a number of ways not to write every single number. E.g.: `for (int i = 1; i <= 500; ++i) { numbers.put(i); }` puts the numbers from 1 to 500, inclusive, in the array. If you already have the numbers in another array, the code to copy from the regular array to the JSON array is similar to this. E.g.: `int[] myNumbers; /*...*/ for (int i = 0; i < myNumbers.length; ++i) { numbers.put(myNumbers[i]); }` – afsantos Nov 20 '13 at 09:58
3

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()`?

Community
  • 1
  • 1
jumps4fun
  • 3,994
  • 10
  • 50
  • 96
1

May, 2023

Java :

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

Kotlin :

val intArr = Array(jsonArr.length()) {jsonArr.getInt(it)}
  • intArr is an Array<Int>
  • it The High-order function is called for each array element sequentially starting from the first one. It should return the value for an array element given its index.
ucMedia
  • 4,105
  • 4
  • 38
  • 46
-1

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);
-2

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".

TR1
  • 323
  • 1
  • 9