Java 如何将 JSONArray 转换为 int 数组?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20068852/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 22:51:06  来源:igfitidea点击:

How to cast JSONArray to int array?

javajson

提问by volly

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

我的方法有问题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 intarray, [1, 2, 3, 4], instead of the JSON

在客户端,我想得到一个int数组[1, 2, 3, 4],而不是 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[]).

我的方法返回 a JSONObject,但我想从中提取数字,以便使用这些(例如作为int[])执行计算。



I reveive function as a JSONObject.

我将函数作为 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[]

然后我收到错误:无法从 JSONObject 转换为 int[]

2 other way

2 其他方式

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

这一次我得到:无法从 JSONArray 转换为 int[]...

It doesn't work anyway..

反正也行不通。。

采纳答案by afsantos

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

我从来没有用过这个,我也没有测试过,但看着你的代码和文档JSONObject,并JSONArray,这是我的建议。

// 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 optIntreturns 0when the value does not exist, or isn't an integer.

这应该适用于您的情况。在更严重的应用程序,你可能要检查如果值确实是整数,作为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.

获取与索引关联的可选 int 值。如果索引没有值,或者值不是数字且无法转换为数字,则返回零。

回答by TR1

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

或者遍历数组“数字”并将每个单独放入“结果”中。

回答by jumps4fun

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:

如果您可以接受 List 作为结果,也可以接受使用 Gson,则有一种非常简单的方法可以做到这一点,只需几行代码:

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

我意识到这并不完全是您所要求的,但根据我的经验,整数列表可以以与基本 int[] 相同的许多方式使用。有关如何将链表转换为数组的更多信息,可以在此处找到:如何使用 `toArray()` 将链表转换为数组?

回答by Aniket Patil

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

回答by ucMedia

Here is a simple methodthat handles JSONArrayconverting to Int Array:

这是一个处理转换为的简单方法JSONArrayInt 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;
}