简体   繁体   中英

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

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

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

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.

Thanks for any help!

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

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

JSONArray mJSONArray = new JSONArray();

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

Source: Android Developers doc

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 .

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 JSONObject is your friend.

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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