0

After hours of search and effort i couldn't fix it.So finally seeking your help.

My Json

[
{
    "notice_id": "2",
    "n_header": "Class Test",
    "n_subject": "Class Test from 15-jan",
    "n_datetime": "2014-01-05 09:00:00",
    "noticenum": "NISTA1",
    "n_body": "Dear Students Class test 1 will be held from january 15. \nDetaled Notice will be notified further with timetable",
    "n_removeby": "2014-01-05",
    "n_givenby": "7",
    "nconcerned_id": "1",
    "nconcerned_batch": "2010",
    "nconcerned_degree": "BTECH",
    "nconcerned_section": " "
},
{
    "notice_id": "3",
    "n_header": "Comprehensive Viva",
    "n_subject": "Comprehensive viva from 20-feb",
    "n_datetime": "2014-02-05 10:00:00",
    "noticenum": "NISTB1",
    "n_body": "Students under me for comprehensive\n viva are hereby informed to clear their viva before 20th feb. After 20 feb no viva would be entertained under me.",
    "n_removeby": "2014-02-21",
    "n_givenby": "1",
    "nconcerned_id": "4",
    "nconcerned_batch": "2010",
    "nconcerned_degree": "BTECH",
    "nconcerned_section": "IT"
}
]

However when i see it in my browser it looks like :

a http://www.4shared.com/download/D1UQsmEbce/json.png?lgfp=3000

As you see it breaks up undesirably.As a result when i parse it in my android app i get an exception value <br of type java.lang.String can't be converted to JSONArray which i believe because of this linebreak issue only.

what I have tried

I tried many things including preg_replace,str_replace etc in order to escape \r\n or <br> etc but couldn't get it work for me.Finally i have a function which i am using like this :

function parse($text) {

$text = str_replace("\r\n", "\n", $text);
$text = str_replace("\r", "\n", $text);
$text = trim( preg_replace( '/\s+/', '<br/>', $text));
// JSON requires new line characters be escaped
 $text = str_replace("\n", "\\n", $text);
return $text;

}

I am writing a query to retrieve data from postgresql database.Hence running the following loop.

for ($i=0; $i<$rows; $i++)
{

$row = pg_fetch_array($result, $i, PGSQL_ASSOC);

$json['notice_id'] = trim(strip_tags($row['notice_id']));
$json['n_header'] = trim(strip_tags($row['n_header']));
$json['n_subject'] = trim(strip_tags($row['n_subject']));
$json['n_datetime'] = trim(strip_tags($row['n_datetime']));
$json['noticenum'] = trim(strip_tags($row['noticenum']));
$json['n_body'] = trim(strip_tags($row['n_body']));
$json['n_removeby']=  trim(strip_tags($row['n_removeby']));
$json['n_givenby'] = trim(strip_tags($row['n_givenby']));
$json['nconcerned_id'] = trim(strip_tags($row['nconcerned_id']));
$json['notice_id'] = trim(strip_tags($row['notice_id']));
$json['nconcerned_batch'] = trim(strip_tags($row['nconcerned_batch']));
$json['nconcerned_degree'] = trim(strip_tags($row['nconcerned_degree']));
$json['nconcerned_section'] = trim(strip_tags($row['nconcerned_section']));

parse($json['notice_id']); 
parse($json['n_header']); 
parse($json['n_subject']); 
parse($json['n_datetime']); 
parse($json['noticenum']); 
parse($json['n_removeby']); 
parse($json['n_givenby']); 
parse($json['nconcerned_id']); 
parse($json['notice_id']); 
parse($json['nconcerned_batch']); 
parse($json['nconcerned_degree']); 
parse($json['nconcerned_section']); 


$data[] = $json;


}

$h = json_encode($data);

echo $h ;


}

Question

How could i get rid of this issue and get a neat json which won't result in any jsonexception?

Note:

I checked carefully many times for linebreaks there.But there are no linebreaks (\n) etc in my database.

Edited Code

$data = array ();
for ($i=0; $i<$rows; $i++)
{

$row = pg_fetch_array($result, $i, PGSQL_ASSOC);

$json['notice_id'] = $row['notice_id'];
$json['n_header'] = $row['n_header'];
$json['n_subject'] = $row['n_subject'];
$json['n_datetime'] = $row['n_datetime'];
$json['noticenum'] = $row['noticenum'];
$json['n_body'] = $row['n_body'];
$json['n_removeby']=  $row['n_removeby'];
$json['n_givenby'] = $row['n_givenby'];
$json['nconcerned_id'] = $row['nconcerned_id'];
$json['notice_id'] = $row['notice_id'];
$json['nconcerned_batch'] = $row['nconcerned_batch'];
$json['nconcerned_degree'] = $row['nconcerned_degree'];
$json['nconcerned_section'] = $row['nconcerned_section'];


$json['notice_id']=parse($json['notice_id']); 
$json['n_header']=parse($json['n_header']); 
$json['n_subject']= parse($json['n_subject']); 
$json['n_datetime']=parse($json['n_datetime']); 
$json['noticenum']=parse($json['noticenum']); 
$json['n_removeby']=parse($json['n_removeby']); 
$json['n_givenby']=parse($json['n_givenby']); 
$json['nconcerned_id']=parse($json['nconcerned_id']); 
$json['notice_id']=parse($json['notice_id']); 
$json['nconcerned_batch']=parse($json['nconcerned_batch']); 
$json['nconcerned_degree']=parse($json['nconcerned_degree']); 
$json['nconcerned_section']=parse($json['nconcerned_section']); 


$data[] = $json;

}

$h = json_encode($data);

echo $h ;

output in browser now

a http://www.4shared.com/download/C4lUKR-1ba/json1.png?lgfp=3000

Here is another json which shows up neatly in my browser.

a http://www.4shared.com/download/tNWhDbfuce/ajson.png?lgfp=3000

It's strange why the other one not having a linebreak!

Weird Solution

I am not sure what solved this problem.But when i changed the url which i was using to execute my php file and it worked for me.Please refer here

Community
  • 1
  • 1
Sash_KP
  • 5,551
  • 2
  • 25
  • 34

3 Answers3

4

You're misinterpreting what your browser is displaying. Remember that JSON is essentially plain text, but your browser is trying to display it as HTML. \n chars are NOT honored by HTML-mode displays, and they will wrap the text at the first appropriate space character. JSON can perfectly well keep \n chars inside its strings without any trouble.

Most likely your <br> error is coming from the <br> insertion you're doing in your preg_replace call, because there are NO <br> tags in the original JSON. In other words, you're causing the very error you're trying to fix, by trying to fix the error which wouldn't exist if you weren't trying to fix it.

elixenide
  • 44,308
  • 16
  • 74
  • 100
Marc B
  • 356,200
  • 43
  • 426
  • 500
  • 2
    As a follow-up, try adding this PHP code before your HTML output: `header("Content-Type: application/json;charset=UTF-8");` – Scott Arciszewski Feb 26 '14 at 21:14
  • well i never see this kind of linebreak for json in my browser.Other php files having different queries are showing in a neat way.So i assumed what i have mentioned.And even if i comment out the `parse` function i get the same output json and same `exception` in my android app. – Sash_KP Feb 26 '14 at 21:28
1

OK based on your inputs i did complete working example depending on some answer here at stack overflow , Parse JSON from URLon android.

PHP Part
i have your data so i did example like this

<?php

$row = array ( 
    "notice_id" => "2",
    "n_header" => "Class Test",
    "n_subject" => "Class Test from 15-jan",
    "n_datetime" => "2014-01-05 09:00:00",
    "noticenum" => "NISTA1",
    "n_body" => "Dear Students Class test 1 will be held from january 15. \nDetaled Notice will be notified further with timetable",
    "n_removeby" => "2014-01-05",
    "n_givenby" => "7",
    "nconcerned_id" => "1",
    "nconcerned_batch" => "2010",
    "nconcerned_degree" => "BTECH",
    "nconcerned_section" => " ");
$row2 = array ("notice_id" => "3",
    "n_header" => "Comprehensive Viva",
    "n_subject" => "Comprehensive viva from 20-feb",
    "n_datetime" => "2014-02-05 10:00:00",
    "noticenum" => "NISTB1",
    "n_body" => "Students under me for comprehensive\n viva are hereby informed to clear their viva before 20th feb. After 20 feb no viva would be entertained under me.",
    "n_removeby" => "2014-02-21",
    "n_givenby" => "1",
    "nconcerned_id" => "4",
    "nconcerned_batch" => "2010",
    "nconcerned_degree" => "BTECH",
    "nconcerned_section" => "IT");
$data [] =$row;
$data [] = $row2;
echo json_encode ($data);

Android Part

class MyAsyncTask extends AsyncTask<String, String, Void> {

        private ProgressDialog progressDialog = new ProgressDialog(MainActivity.this);
        InputStream inputStream = null;
        String result = ""; 

        protected void onPreExecute() {
            progressDialog.setMessage("Downloading your data...");
            progressDialog.show();
            progressDialog.setOnCancelListener(new OnCancelListener() {
                public void onCancel(DialogInterface arg0) {
                    MyAsyncTask.this.cancel(true);
                }
            });
        }

        @Override
        protected Void doInBackground(String... params) {

            String url_select = "http://192.168.10.206/test.php";

                    ArrayList<NameValuePair> param = new ArrayList<NameValuePair>();

            try {
                // Set up HTTP post

                // HttpClient is more then less deprecated. Need to change to URLConnection
                HttpClient httpClient = new DefaultHttpClient();

                HttpPost httpPost = new HttpPost(url_select);
                httpPost.setEntity(new UrlEncodedFormEntity(param));
                HttpResponse httpResponse = httpClient.execute(httpPost);
                HttpEntity httpEntity = httpResponse.getEntity();

                // Read content & Log
                inputStream = httpEntity.getContent();
            } catch (UnsupportedEncodingException e1) {
                Log.e("UnsupportedEncodingException", e1.toString());
                e1.printStackTrace();
            } catch (ClientProtocolException e2) {
                Log.e("ClientProtocolException", e2.toString());
                e2.printStackTrace();
            } catch (IllegalStateException e3) {
                Log.e("IllegalStateException", e3.toString());
                e3.printStackTrace();
            } catch (IOException e4) {
                Log.e("IOException", e4.toString());
                e4.printStackTrace();
            }
            // Convert response to string using String Builder
            try {
                BufferedReader bReader = new BufferedReader(new InputStreamReader(inputStream, "iso-8859-1"), 8);
                StringBuilder sBuilder = new StringBuilder();

                String line = null;
                while ((line = bReader.readLine()) != null) {
                    sBuilder.append(line + "\n");
                }

                inputStream.close();
                result = sBuilder.toString();

            } catch (Exception e) {
                Log.e("StringBuilding & BufferedReader", "Error converting result " + e.toString());
            }
            return null;
        } // protected Void doInBackground(String... params)

        protected void onPostExecute(Void v) {
            //parse JSON data
            try {
                JSONArray jArray = new JSONArray(result);    
                for(int i=0; i < jArray.length(); i++) {

                    JSONObject jObject = jArray.getJSONObject(i);

                    String name = jObject.getString("n_body");
                    String tab1_text = jObject.getString("n_removeby");
                    int active = jObject.getInt("notice_id");
                    Log.i("NAME",name);
                    Log.i("REMOVE",tab1_text);
                } // End Loop
                this.progressDialog.dismiss();
            } catch (JSONException e) {
                Log.e("JSONException", "Error: " + e.toString());
            } // catch (JSONException e)
        } // protected void onPostExecute(Void v)
    } //class MyAsyncTask extends AsyncTask<String, String, Void>

don't forget to call MyAsync task some where like that.

MyAsyncTask task = new MyAsyncTask();
        task.execute();

And this works very fine,so please review your android code where i believe the issue is from their,Hope this help you.

Community
  • 1
  • 1
Samy Massoud
  • 4,295
  • 2
  • 35
  • 48
  • Okay.Please check my edit.I assigned variables as above.Is that okay to assign the same variables or different ones are required? – Sash_KP Feb 26 '14 at 21:47
  • it's ok to do this , what is the result you get ? – Samy Massoud Feb 26 '14 at 21:48
  • Please check my edits.A very slight change has occurred.But the `value
    – Sash_KP Feb 26 '14 at 21:57
  • Also check another pic that i have attached.Can't understand why the other one have a linebreak! – Sash_KP Feb 26 '14 at 22:08
  • Without using `AsynTask` i am able to parse everything correctly now **when i use** `String url = "http://192.168.32.1/Aafois/notice.php?isBatch=2010&section1='IT'";`But when i use `String URL = "http://192.168.32.1/Aafois/notice.php?isBatch="+isbatch+"&section1="+"'"+section1+"'";`I get `JSONException`.`isbatch` and `section1` are 2 string variables which are urlencoded too. – Sash_KP Feb 27 '14 at 15:13
  • try remove single quotes URL = "http://192.168.32.1/Aafois/notice.php? isBatch="+isbatch+"&section1="+sectio‌​n1; – Samy Massoud Feb 27 '14 at 18:02
  • I was able to work it out by checking the variables `isbatch` and `section1`.These were returning null.Thanks for your help. – Sash_KP Feb 27 '14 at 18:04
0

You just have to add new lines before decoding it and it will work 100%:

$text = str_replace("\r\n", "\n", $text);
Olcay Ertaş
  • 5,987
  • 8
  • 76
  • 112
Fahad Rana
  • 11
  • 4