Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to cast JSONArray to int array?

Tags:

java

json

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

like image 633
volly Avatar asked Nov 19 '13 10:11

volly


People also ask

How can I turn a JSONArray into a JSON object?

We can also add a JSONArray to JSONObject. We need to add a few items to an ArrayList first and pass this list to the put() method of JSONArray class and finally add this array to JSONObject using the put() method.

How do I get items from JSONArray?

JSONArray jsonArray = (JSONArray) jsonObject. get("contact"); The iterator() method of the JSONArray class returns an Iterator object using which you can iterate the contents of the current array.

How do I traverse JSONArray?

1) Create a Maven project and add json dependency in POM. xml file. 2) Create a string of JSON data which we convert into JSON object to manipulate its data. 3) After that, we get the JSON Array from the JSON Object using getJSONArray() method and store it into a variable of type JSONArray.

Is JSONArray a JSON object?

JSONObject and JSONArray are the two common classes usually available in most of the JSON processing libraries. A JSONObject stores unordered key-value pairs, much like a Java Map implementation. A JSONArray, on the other hand, is an ordered sequence of values much like a List or a Vector in Java.


2 Answers

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.

like image 73
afsantos Avatar answered Sep 27 '22 18:09

afsantos


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

like image 28
jumps4fun Avatar answered Sep 27 '22 19:09

jumps4fun