Trying to store JSON separately

Go To


I am trying to parse some JSON into separate objects in Android. The objects are separated by an end brace, no whitespace, then a start brace ("end of first}{start of second"). So far, my code allows me to find where these points are in the JSON, but I can't figure out what methods to use in order to split the objects and then store them. Here's my code that gets the JSON and then attempts to parse:

public ArrayList<String> 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) {
    } catch (ClientProtocolException e) {
    } catch (IOException e) {

    try {
        ArrayList<String> questionsList = new ArrayList<String>();
        int count = 0;
        BufferedReader reader = new BufferedReader(new InputStreamReader(
                is, "iso-8859-1"), 8);
        StringBuilder sb = new StringBuilder();
        String line = null;
        String newLine = null;
        String newLine2 = null;
        int previousJ = 0;
        if ((line = reader.readLine()) != null) {
            for(int j = 0; j < line.length(); j++) {
                while (line.charAt(j) == '}' && line.charAt(j+1) == '{') {
                    //everything before j = 1 string
                    //everything after gets deleted because I can't think
                    //of anything better, yet                       
                    sb.delete(j+1, sb.length());
                    line = sb.toString();
                    questionsList.add(count, line);
                    //line = line.split("\\}\\{");
                    Log.v("forintbs", questionsList.toString());
        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 null; 

Obviously the method is returning null for now, because it wouldn't matter anyways. So far, when I look in the Log to see the printout, my arraylist is one long and has properly acquired the string as expected - but the rest of the original data is also deleted as expected. I've left my code exactly as is so you can see what I've tried. Does anyone have any suggestions? Here's some of the sample JSON:

{"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"}

I'd have no problem not using an ArrayList, but instead an array of JSON Objects. I am simply trying as suggested in a question I asked yesterday.

EDIT~ Here's my PHP Script:


define("DB_HOST", "localhost");
define("DB_USER", "*");
define("DB_PASSWORD", "*");
define("DB_DATABASE", "*");

mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);
$sql=mysql_query("select * from QUESTIONS where CATEGORY like 'elections'");
while($row=mysql_fetch_assoc($sql)) {
foreach($output as $value) {
echo json_encode($value);
2012-04-04 04:06
by Davek804
Your sample JSON is not actually valid json. Why not simply return an array of objects, so you have [0:{first object}, 1:{second object}, etc...], which would be valid json and not require any extra parsing - Marc B 2012-04-04 04:08
@MarcB I was not aware of that. Could you please provide a bit of a code suggestion, if possible? I've edited the post to show my current PHP script. Thanks so much (I'm new to SQL/PHP, so the fact that it's not valid JSON doesn't surpise me...) - Davek804 2012-04-04 04:13
json is simply a slightly more strict representation of a javascript variable's definition. e.g. given, var x = ..., json is the ... portion. If whatever json you're generating can't be pasted directly into a variable assignment in some real javascript code and get parsed/executed, then it's not valid json. Instead of doing a series of echo json_encode($something), you build a monolithic data structure in PHP, then json_encode the whole thing - Marc B 2012-04-04 04:16
Well, I'm not even close to understanding how to build a monolithic data structure in PHP, as I barely know what that means. I managed to create a login/register system by following a tutorial and then manipulating it to support ASynctask, but clearly if I wish to be able to get data from other tables, I have much learning to do.. - Davek804 2012-04-04 04:23
$x = array(0 => array('child data'), 1 => array('more child data'), etc...); echo json_encode($x);. There, one semi-pseudo-code monolithic data structure. It just means to build your individual data structures and embed them in another containing structure. You then encode that container, and the whole thing becomes a single valid json string - Marc B 2012-04-04 04:26


As Marc B said, I needed stronger/more correct PHP code. Another Stack Overflow user helped me refine the code that Marc B assisted me in understanding. Now the JSON is returned as properly encoded data, but I still have not determined how to parse it into separate objects. I will get there soon.

Here is the partial solution:

2012-04-04 21:38
by Davek804