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.
-
is it the full JSON data?Spring Breaker– Spring Breaker2014年04月21日 15:58:56 +00:00Commented Apr 21, 2014 at 15:58
-
yes, the top coding is the json data sent by the php file.user3485703– user34857032014年04月21日 16:03:20 +00:00Commented Apr 21, 2014 at 16:03
-
I just want to get the second array object values in java/android.user3485703– user34857032014年04月21日 16:04:03 +00:00Commented Apr 21, 2014 at 16:04
-
is this really your JSON? it isnt validmeda– meda2014年04月21日 16:17:58 +00:00Commented Apr 21, 2014 at 16:17
-
@user3485703: I don't think it should be the complete json data.Do check it again.Spring Breaker– Spring Breaker2014年04月21日 16:29:36 +00:00Commented Apr 21, 2014 at 16:29
2 Answers 2
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();
}
Comments
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.