Reputation: 2804
My PHP successfully returns JSON from my SQL table. But my Android code stores it all in one String. Should it indeed be stored in one string and then parsed out into multiple objects? Here's the relevant code.
First, what the stored result looks like currently:
04-04 21:26:00.542: V/line(1230): [{"category":"elections","id":"0","title":"Who will you vote for in November's Presidential election?","published":"2012-04-02","enddate":"2012-04-30","responsetype":"0"},{"category":"elections","id":"2","title":"Question title, ladies and gents","published":"2012-04-02","enddate":"2012-04-30","responsetype":"1"}]
So that obviously all just stores as one huge string, even though it's two table rows. Here is the code that produces that line for me:
public JSONObject getQuestionJSONFromUrl(String url, List<NameValuePair> params) {
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
Log.v("while", line);
sb.append(line + "\n");
//Log.v("err", line);
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
Obviously I get all sorts of errors after my WHILE loop right now. I've spent a couple days trying to sort it out, but only just gotten the PHP to return proper JSON (which it didn't previously). I expect I need a JSONArray, with each of the JSON results being stored inside one index of the Array - so I expect to need to change the return of this method to a JSONArray, is that correct? Can anyone lead me down the right path for parsing the JSON that I receive from my PHP script?
Upvotes: 2
Views: 333
Reputation: 137362
Yes, this is correct. You need to parse it as JSONArray, as that's what it is. For example (ignoring exceptions etc.):
JSONArray jarr = new JSONArray(jsonString);
for (int i = 0; i < jarr.length(); ++i) {
JSONObject jobj = jarr.getJSONObject(i);
// work with object
}
Upvotes: 1