TheMcMurder
TheMcMurder

Reputation: 758

Convert JSON string in array format into an array in java

I'm trying to take the following string that I got as a json object:

 [
    {
        "id": "picture1",
        "caption": "sample caption",
        "picname": "sample picture name"
      }
 ]

and turn it into a array so I can populate a list

I've tried turning it into a jsonarray by doing this:

JSONArray myjsonarray = myjson.toJSONArray(string_containing_json_above); 

but that didn't seem to work.

==============

Here is full code with the working solution

myjson = new JSONObject(temp);
String String_that_should_be_array = myjson.getString("piclist");
JSONArray myjsonarray = new JSONArray(String_that_should_be_array);
For(int i = 0; i < myjsonarray.length(); i++){
    JSONObject tempJSONobj = myjsonarray.getJSONObject(i);
    showToast(tempJSONobj.get("caption").toString());
}

temp is the json from the server

Upvotes: 1

Views: 10668

Answers (3)

kyogs
kyogs

Reputation: 6836

here you get JSONArray so change

JSONArray myjsonarray = myjson.toJSONArray(temparray); 

line as shown below

JSONArray jsonArray = new JSONArray(readlocationFeed);

and after

 JSONArray jsonArray =  new JSONArray(readlocationFeed);

    for (int i = 0; i < jsonArray.length(); i++) {
        JSONObject explrObject = jsonArray.getJSONObject(i);
        explrObject.getString("caption");
}

Upvotes: 3

dckuehn
dckuehn

Reputation: 2475

JSONArray isn't working because the JSON you provided is not an array. You can read more about JSON syntax here: http://www.w3schools.com/json/json_syntax.asp

In the meantime, you could manually create your array by paring the JSON one string at a time.

JSONObject strings = new JSONObject(jsonString);
String array[] = new String[5];

if (jsonString.has("id"){
    array[0] = jsonString.getString("id");
}
if (jsonString.has("caption"){
    array[1] = jsonString.getString("caption");
}
...

etc.

Upvotes: 0

Paresh Mayani
Paresh Mayani

Reputation: 128428

Issue is here:

JSONArray myjsonarray = myjson.toJSONArray(temparray); 

Solution:

JSONArray myjsonarray = new JSONArray(myJSON);   
// myJSON is String

Now here you are having JSONArray, iterate over it and prepare ArrayList of whatever types of you want.

Upvotes: 4

Related Questions