1

I am facing a problem, a valid JSON string cannot become a JSON object.

I have tested the response coming from the server, it is a valid JSON.

I have checked on the internet, it is about the problem of UTF-8 with DOM. But even I changed the charset in Notepad++ into UTF-8 with no DOM, the same error still coming out.

My codes:

<?php
    require_once("Connection/conn.php");


    //parse JSON and get input
    $json_string = $_POST['json'];
    $json_associative_array = json_decode($json_string,true);

    $userId = $json_associative_array["userId"];
    $password = $json_associative_array["password"];
    $userType = $json_associative_array["userType"];    

    //get the resources
    $json_output_array = array();

    $sql = "SELECT * FROM account WHERE userId = '$userId' AND password = '$password' AND userType = '$userType'";  
    $result = mysql_query($sql);  

    //access success?
    if (!$result) {
        die('Invalid query: ' . mysql_error());
        $json_output_array["status"] = "query failed";
    }
    else{
        $json_output_array["status"] = "query success";
    }

    //find the particular user?
    if (mysql_num_rows($result) > 0){
        $json_output_array["valid"] = "yes";
    }
    else{
        $json_output_array["valid"] = "no";
    }

    //output JSON 
    echo json_encode($json_output_array);
?>

Android codes:

public boolean login() {
        // instantiates httpclient to make request
        DefaultHttpClient httpClient = new DefaultHttpClient();

        // url with the post data
        String url = SERVER_IP + "/gc/login.php";

        JSONObject holder = new JSONObject();
        try {
            holder.put("userId", "S1");
            holder.put("password", "s12345");
            holder.put("userType", "supervisor");
        } catch (JSONException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }

        Log.d("JSON", holder.toString());


        // HttpPost
        HttpPost httpPost = new HttpPost(url);


        //FormEntity
        ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
        nameValuePairs.add(new BasicNameValuePair("json", holder.toString()));

        try {
            httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
        } catch (UnsupportedEncodingException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }

        // execution and response
        boolean valid = false; 
        try {
            HttpResponse response = httpClient.execute(httpPost);

            Log.d("post request", "finished execueted");
            String responseString = getHttpResponseContent(response);
            Log.d("post result", responseString);

            //parse JSON
            JSONObject jsonComeBack = new JSONObject(responseString);
            String validString = jsonComeBack.getString("valid");
            valid = (validString.equals("yes"))?true:false;

        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }



        return valid;

    }

    private String getHttpResponseContent(HttpResponse response) {

        String responseString = "";

        try {
            BufferedReader rd = new BufferedReader(new InputStreamReader(
                    response.getEntity().getContent()));

            String line = "";

            while ((line = rd.readLine()) != null) {
                responseString += line ;
            }
            rd.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return responseString;
    }

JSON come from server:

{
    "status": "query success",
    "valid": "yes"
}

unformat JSON:

{"status":"query success","valid":"yes"}

When I copy this into notepad++, it becomes ?{"status":"query success","valid":"yes"} It seems that there is a invisible character .

R G
  • 461
  • 3
  • 15
code4j
  • 4,208
  • 5
  • 34
  • 51
  • You should post your JSON results. It looks like you're trying to convert a JSON array to a JSON object - which wouldn't work. – dispake Nov 13 '12 at 21:07
  • Have you tried adding a encoding type for your UrlEncodedFormEntity call? UrlEncodedFormEntity(pairs, HTTP.UTF_8); – dispake Nov 13 '12 at 21:47
  • First of all you should post what the error actually is, and on which part of the two it occurrs? Currently nobody knows whether PHP has the error or Android. Also mention any error text you encounter. Additionally it would be really good to actually see the generated JSON strings UNFORMATTED. They usually do not come with newlines and pretty-printed. – Sven Nov 13 '12 at 21:54
  • Apologies, I made the usual error of ignoring the headline - it is too far away from the posting text. – Sven Nov 13 '12 at 22:08
  • @Sven it doesn't matter :) I always ignore the headline too. I have updated my question, there is also a discovery when I copied the text from log into notepad++ – code4j Nov 13 '12 at 22:23

2 Answers2

2

I fixed it with the solution provided by MuhammedPasha, which substring the JSON string to remove invisible character. And I substring the JSON String from 1 to fix my problem.

There is a way to detect those invisible characters, copy the log result into notepad++.(copy! no typing!) If there are any ?(question mark), they indicates that there are some invisible character.

Community
  • 1
  • 1
code4j
  • 4,208
  • 5
  • 34
  • 51
1

I had a same problem. Maybe you need to save without unicode signature (BOM).

Bold Bat
  • 889
  • 1
  • 6
  • 6
  • actually I have found the cause of this problem. I have saved this PHP with UTF-8 without BOM, but the PHP included is still saved as UTF-8 with DOM – code4j Feb 24 '13 at 07:07