【问题标题】:How to convert int Array to JSON String in Android?如何在 Android 中将 int Array 转换为 JSON String?
【发布时间】:2013-11-21 09:56:14
【问题描述】:

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

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

我尝试了什么:

我试过这段代码:

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

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

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

我想这样做的原因:

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

感谢您的帮助!

【问题讨论】:

    标签: java android arrays json


    【解决方案1】:

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

    试试JSONArray mJSONArray = new JSONArray(image_ids_primitive);

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

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

    来源:Android Developers doc

    【讨论】:

    • 谢谢!但这给出了错误(即使在 try/catch 中):java.lang.NoSuchMethodError: org.json.JSONArray.<init> Edit:我猜在 API 级别 19 中添加了 (Object array) 的构造函数。所以我必须迭代并构造字符串手动?
    • 这适用于所有版本,是的。只需创建一个空 JSONArray 并在一个小的 for 循环中 mJSONArray.put(image_ids_primitive[i]) 整数。我会编辑答案。
    【解决方案2】:

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

    或者,为了快速破解:

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

    打印出来

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

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

    【讨论】:

      【解决方案3】:

      试试这个方法

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

      【讨论】:

        【解决方案4】:
        // 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());
        

        【讨论】:

          【解决方案5】:
          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
          

          【讨论】:

            【解决方案6】:

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

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

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

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

            【讨论】:

            • String.valueOf(i) 可以是 i。我把它留下来为您提供您在问题中所要求的确切内容。 Json 可以将整数作为值保存,这样您就不必在第二个活动中解析回整数。
            猜你喜欢
            • 2018-05-15
            • 2018-11-26
            • 1970-01-01
            • 1970-01-01
            • 2017-01-30
            • 2011-10-13
            • 2016-06-10
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多