10

I have a Json String and I am trying to convert it to an array in Java.

public void DisplaySubjects(String subjects)
     {
         JSONObject jsonResponse;
         jsonResponse = new JSONObject(subjects));

Thats as far as I get.I'm not even sure if I have to create a object first.

What I will need to do eventuallay is attach it to a ArrayAdapter in an android app.

Thanks

Prizoff
  • 4,486
  • 4
  • 41
  • 69
mike628
  • 45,873
  • 18
  • 40
  • 57
  • Relevant : http://stackoverflow.com/questions/5245840/how-to-convert-string-to-jsonobject-in-java – Sid Jul 17 '12 at 16:59

3 Answers3

16

Something like this:

ArrayList<String> jsonStringToArray(String jsonString) throws JSONException {

    ArrayList<String> stringArray = new ArrayList<String>();

    JSONArray jsonArray = new JSONArray(jsonString);

    for (int i = 0; i < jsonArray.length(); i++) {
        stringArray.add(jsonArray.getString(i));
    }

    return stringArray;
}
Prizoff
  • 4,486
  • 4
  • 41
  • 69
2

You could try something like:

new JSONArray(jsonString)

or if it is a property:

jsonObject.getJSONArray(propertyName)
Francisco Spaeth
  • 23,493
  • 7
  • 67
  • 106
1

You need to make JSON object first.

For example,

JSONObject jsonObject = new JSONObject(resp);

jsonObject may contains other JSON Objects or JSON array.

How to convert the JSON depends on the String.

There is a complete example with some explanation about JSON String to JSON array can be found at http://www.hemelix.com/JSONHandling.

Sulthan Allaudeen
  • 11,330
  • 12
  • 48
  • 63
RotatingWheel
  • 1,023
  • 14
  • 27