Java 如何在 Android 中将 int Array 转换为 JSON String?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20117603/
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 23:16:34  来源:igfitidea点击:

How to convert int Array to JSON String in Android?

javaandroidarraysjson

提问by mobilGelistirici

I expected to find this question around, but I couldn't. Maybe I'm Googling the wrong thing.

我希望能找到这个问题,但我不能。也许我在谷歌上搜索错误的东西。

I have a primitive integer array (int[]), and I want to convert this into a String, that is "JSON-Parseable", to be converted back to the same int[].

我有一个原始整数数组 ( int[]),我想将它转换为一个String,即“JSON-Parseable”,然后再转换回相同的int[].

What have I tried :

我试过什么:

I tried this code :

我试过这个代码:

// int[] image_ids_primitive = ...    

JSONArray mJSONArray = new JSONArray(Arrays.asList(image_ids_primitive));
String jSONString = mJSONArray.toString();
Prefs.init(getApplicationContext());
Prefs.addStringProperty("active_project_image_ids", jSONString);
// Note: Prefs is a nice Class found in StackOverflow, that works properly. 

When I printed the jSONStringvariable, it has the value : ["[I@40558d08"]

当我打印jSONString变量时,它的值是:["[I@40558d08"]

whereas, I expected a proper JSON String like this : {"1" : "424242" , "2":"434343"}not sure about the quotation marks, but you get the idea.

然而,我期望像这样一个正确的 JSON 字符串:{"1" : "424242" , "2":"434343"}不确定引号,但你明白了。

The reason I want to do this :

我想这样做的原因:

I want to keep track of local images (in drawable folder), so I store their id's in the int array, then I want to store this array, in the form of a JSON String, which will be later parsed by another activity. And I know I can achieve this with Intent extras. But I have to do it with SharedPreferences.

我想跟踪本地图像(在 drawable 文件夹中),所以我将它们的 id 存储在 int 数组中,然后我想以 JSON 字符串的形式存储这个数组,稍后将被另一个活动解析。我知道我可以通过 Intent extras 实现这一点。但我必须用 SharedPreferences 来做。

Thanks for any help!

谢谢你的帮助!

回答by Biraj Zalavadia

Try this way

试试这个方法

int [] arr = {12131,234234,234234,234234,2342432};

        JSONObject jsonObj = new JSONObject();

        for (int i = 0; i < arr.length; i++) {
            try {
                jsonObj.put(""+(i+1), ""+arr[1]);
            } catch (Exception e) {
            }
        }
        System.out.println("JsonString : " + jsonObj.toString());

回答by android_dev

// If you wants the data in the format of array use JSONArray.
    JSONArray jsonarray = new JSONArray();
    //[1,2,1,] etc..
    for (int i = 0; i < data.length; i++) {
        jsonarray.put(data[i]);
    }
    System.out.println("Prints the Json Object data :"+jsonarray.toString());
    JSONObject jsonObject=new JSONObject();
    // If you want the data in key value pairs use json object.
    // i.e {"1":"254"} etc..
    for(int i=0;i<data.length;i++){
        try {
            jsonObject.put(""+i, data[i]);
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    System.out.println("Prints the Json Object data :"+jsonObject.toString());

回答by Sietse van der Molen

You don't have to instantiate the JSONArray with Arrays.asList. It can take a normal primitive array.

您不必使用 Arrays.asList 实例化 JSONArray。它可以采用普通的原始数组。

Try JSONArray mJSONArray = new JSONArray(image_ids_primitive);

尝试 JSONArray mJSONArray = new JSONArray(image_ids_primitive);

If you are using an API level below 19, one easy method would just be to loop over the int array and put them.

如果您使用的 API 级别低于 19,一种简单的方法就是循环遍历 int 数组并将它们放入。

JSONArray mJSONArray = new JSONArray();

for(int value : image_ids_primitive)
{
    mJSONArray.put(value);
}

Source: Android Developers doc

来源:Android 开发者文档

回答by Suhail Mehta

itertate this through the int array and you will get the json string

JSONStringer img = null ;

  img = new JSONStringer() .object() .key("ObjectNAme")
                  .object() .key("something").value(yourIntarrayAtIndex0)
                  .key("something").value(yourIntarrayAtIndex1) .key("something").value(yourIntarrayAtIndex2)
                  .key("something").value(yourIntarrayAtIndex3) 
                  .endObject() .endObject();

                  String se = img.toString();

Here se is your json string in string format

回答by speedynomads

This code will achieve what you are after...

这段代码将实现你所追求的......

int index = 0;
final int[] array = { 100, 200, 203, 4578 };
final JSONObject jsonObject = new JSONObject();
try {
    for (int i : array) {
        jsonObject.put(String.valueOf(index), String.valueOf(i));
        index++;
    }
} catch (JSONException e) {
    e.printStackTrace();
}                       
Log.d("YOUR_TAG", jsonObject.toString());

This will give you {"3" : "203", "2" : "200", "1": "100", "4": "4578"} as a string.

这会给你 {"3" : "203", "2" : "200", "1": "100", "4": "4578"} 作为字符串。

Not exactly sure why its not in the exact order, but sorting by a key is quite easy.

不完全确定为什么它不是按确切顺序排列的,但是按键排序很容易。

回答by Vlad

If you want a JSON array and not necessarily an object, you can use JSONArray.

如果你想要一个 JSON 数组而不一定是一个对象,你可以使用JSONArray.

Alternatively, for a quick hack:

或者,为了快速破解:

System.out.println(java.util.Arrays.toString(new int[]{1,2,3,4,5,6,7}));

prints out

打印出来

[1, 2, 3, 4, 5, 6, 7] 

which is valid JSON. If you want anything more complicated than that, obviously JSONObjectis your friend.

这是有效的 JSON。如果你想要比这更复杂的东西,显然JSONObject是你的朋友。