Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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!

share|improve this question

6 Answers 6

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());
share|improve this answer
// 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());
share|improve this answer
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
share|improve this answer

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

share|improve this answer
    
Thanks! But this gives the error (even inside try/catch) : java.lang.NoSuchMethodError: org.json.JSONArray.<init> Edit: I guess the constructor with (Object array) is added in API Level 19. So do I have to iterate and construct the String manually ? –  mobilGelistirici Nov 21 '13 at 10:12
    
That would work an all versions, yes. Just create an empty JSONArray and in a small for loop mJSONArray.put(image_ids_primitive[i]) the ints. I'll edit the answer. –  Sietse van der Molen Nov 21 '13 at 10:17

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.

share|improve this answer
    
String.valueOf(i) can just be i. I left it in to provide you with exactly what you asked for in your question. Json can hold ints as values, this is would save you having to parse back to an integer in your second activity. –  domji84 Nov 21 '13 at 10:28

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.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.