简体   繁体   English

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

[英]How to convert int Array to JSON String in Android?

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 jSONString variable, 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. 我想跟踪本地图像(在drawable文件夹中),因此我将其ID存储在int数组中,然后以JSON字符串的形式存储此数组,稍后将由另一个活动对其进行解析。 And I know I can achieve this with Intent extras. 而且我知道我可以通过Intent Extras实现此目的。 But I have to do it with SharedPreferences. 但是我必须使用SharedPreferences来做。

Thanks for any help! 谢谢你的帮助!

You don't have to instantiate the JSONArray with Arrays.asList. 您不必使用Arrays.asList实例化JSONArray。 It can take a normal primitive array. 它可以采用普通的原始数组。

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开发人员文件

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

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. 这是有效的JSON。 If you want anything more complicated than that, obviously JSONObject is your friend. 如果您想要比这更复杂的事情,显然JSONObject是您的朋友。

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

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. 不能完全确定为什么它的顺序不正确,但是按键排序很容易。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM