I am passing back a JSON object (consisting of an array of strings) from php. I am trying to convert the object into a Java jArray but the string I get back from my php file isn't formed correctly:
String from php (I have 2 entries in my db tips table)
[{"0":"2","id":"2","1":"2","household_id":"2","2":"3","stepgreen_id":"3","3":"tip 1","tip":"tip 1","4":"2011-08-05","dateOfTip":"2011-08-05","5":"3","likes":"3"}]
[{"0":"2","id":"2","1":"2","household_id":"2","2":"3","stepgreen_id":"3","3":"tip 1","tip":"tip 1","4":"2011-08-05","dateOfTip":"2011-08-05","5":"3","likes":"3"},{"0":"91","id":"91","1":"1","household_id":"1","2":"1","stepgreen_id":"1","3":"tip 2","tip":"tip 2","4":"2011-08-04","dateOfTip":"2011-08-04","5":"1","likes":"1"}]
Here is my php code
<?php
// mysql connection, etc....
$query = "SELECT * FROM Tips";
$result = mysql_query($query);
while($row = mysql_fetch_array($result))
{
$output[]=$row;
print(json_encode($output));
}
mysql_close($con);
?>
In Java, I do the following. What happens is that I get back a jArray with only one entry. I expect 2. I'm not sure why the php json object is returning an array of 1 string and a second array of 2 strings. I only expect to receive an array of 2 strings.
try {
InputStream responseData;
responseData = httpEntity.getContent();
js = convertStreamToString(responseData);
Log.v(LOG_TAG, js);
jArray = new JSONArray(js);
JSONObject json_data = null;
Log.v(LOG_TAG, "Arraysize: " + jArray.length());
for (int i = 0; i < jArray.length(); i++) {
Log.v(LOG_TAG, "entering loop");
json_data = jArray.getJSONObject(i);
tip = json_data.getString("tip");
stepgreenId = json_data.getString("stepgreen_id");
dateOfTip = json_data.getString("dateOfTip");
householdId = json_data.getString("household_id");
likes = json_data.getString("likes");
Log.v(LOG_TAG, "Json tip= " + tip + " stepgreen id: " + stepgreenId + " household_id: " + householdId + " likes: " + likes);
}
} catch (IllegalStateException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}