user3485703
user3485703

Reputation: 13

parse json array in android

I need a help... I have a php file which returns me two json Arrays which are as follows:

[{ "id":"1",
   "item":"hammers",
   "aisle":"20"
 }
 { "id":"1",
   "item":"hammers",
   "aisle":"20"
 }]

[{ "id":"1",
   "itemFound":"Your item #item",
   "ThankYou":"and Thank You for using Txtcore!"
 }]

Now, I want to get the second array items in Android. I have the following code now which is like : JSONArray jsonArray = new JSONArray(result);

         for (int   i = 0; i < jsonArray.length(); i++) {
              JSONObject jsonObject = jsonArray.getJSONObject(i);       
            items.add(jsonObject.getString("item"));
            aisles.add(""+jsonObject.getString("item");

         }

But obviously, that returns me the objects from the first array. I want to get the Objects from the second array. Any suggestions.

Upvotes: 0

Views: 96

Answers (2)

Manmohan Badaya
Manmohan Badaya

Reputation: 2336

Your JSON is not valid but u can get your element as follows. It is a solution from many(just a worlaround).

String str = "YOUR_JSON_RESPONSE";
String array[] = str.split("\\[\\{");// 
try {
     JSONArray jsonArray=new JSONArray("[{" + array[2]));
} catch (JSONException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}

Upvotes: 1

Daniel Cerecedo
Daniel Cerecedo

Reputation: 6207

I guess you'll have to do some dirty coding because the data return by the PHP page is not well formed JSON. You could try to transform the JSON data to: { "data" : [ <array_1>, <array_2> ]} And then use the JSON parser. A simple replacement with a regexp could be fine.

  result.replaceAll("\\]\\s*\\[", "], [");
  StringBuffer buffer=new StringBuffer(result);
  buffer.insert(0,"{ \"data\": ");
  buffer.append(" }");
  JSONObject jsonObject = new JSONObject(buffer.toString());
  JSONArray secondArray= jsonObject.getJSONArray("data").getJSONArray(1);

The creation of a valid JSON string can be done in one step with the appropriate regexp. Hope some one with more time can post it here.

Upvotes: 0

Related Questions