2

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?

4
  • JSON's just a transport format. Once you've got the json string in your app, you decode it 'back' to a native data structure. You never directly manipulate the JSON string itself. Commented Apr 4, 2012 at 21:38
  • I understand, Marc B. I suppose my problem (as you can see in the Java above) is that the only effective method I have from reader is readLine(), which stores all the JSON at once into a string. Should I go ahead and parse that string? Commented Apr 4, 2012 at 21:39
  • There are libraries that can deserialize JSON into domain objects, e.g. GSON, which makes this a piece of cake. Commented Apr 4, 2012 at 21:40
  • Thanks Tyler, in the course of sorting this out, I've certainly heard a fair bit about GSON. If it turns out I still have issues with all of this, I very well may look into incorporating that library. Commented Apr 4, 2012 at 21:49

1 Answer 1

1

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
}
Sign up to request clarification or add additional context in comments.

4 Comments

This worked flawlessly. Obviously I'll still need to sort out the code for getTitle, getID, etc etc, but that should be much more straightforward now that I have each JSON piece as its own object. Thank you so much - this has taken three Stack Overflow questions just to be able to sort out how I was supposed to ask all you geniuses for your expert guidance. Much appreciated!
Also, I already catch all the POS exceptions - but if this continues to be a problem, I'll certainly look into an external library like GSON as Tyler said above.
Glad I could help. BTW, from my short experience, when working appropriately with those classes, you should be able to do many things, I don't think you need to move to GSON, but that's a matter of taste :)
Yeah. To be honest, I don't expect I will need to, the solution you put forward is very elegant and should almost never lead to an uncaught exception if I pay attention to my tables.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.