PHP SQL array json encode error when converting to java - php

I am echoing a json set of results back to android:
$result = mysql_query($query) or die(mysql_error());
$resultNo = mysql_num_rows($result);
// check for successful store
if ($result != null) {
$rows = array();
while($r = mysql_fetch_assoc($result)) {
$rows[] = $r;
}
return json_encode($rows);
} else {
return false;
}
}
But when I try to convert the string to a JSONObject at the other end i get:
11-13 22:18:41.990: E/JSON(5330): "[{\"email\":\"fish\"}]"
11-13 22:18:41.990: E/JSON Parser(5330): Error parsing data org.json.JSONException: Value [{"email":"fish"}] of type java.lang.String cannot be converted to JSONObject
I have tried this with a larger result set and thought that it would be something to do with null values however trying it as above with just one value still returns an error.
Any help greatly appreciated
EDIT:
Android methods...
public JSONObject searchPeople(String tower) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("tag", search_tag));
params.add(new BasicNameValuePair("tower", tower));
// getting JSON Object
JSONObject json = jsonParser.getJSONFromUrl(loginURL, params);
// return json
return json;
}
JSON Parser class...
public JSONObject getJSONFromUrl(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) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
Log.e("JSON", json);
} 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;
}

As #MikeBrant mentioned above, you need to pass through JSONArray first.
Replace this:
//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());
}
With this:
// try parse the string to a JSON object
try {
JSONArray jArray = new JSONArray(json);
for(i=0; i < jArray.length(); i++) {
JSONObject jObj = jArray.getJSONObject(i);
Log.i("jObj", "" + jObj.toString());
// Parsing example
String email = jObj.getString("email");
Log.i("email", email);
}
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
PHP w/ str_replace:
$result = mysql_query($query) or die(mysql_error());
$resultNo = mysql_num_rows($result);
// check for successful store
if ($result != null) {
$rows = array();
while($r = mysql_fetch_assoc($result)) {
$rows[] = $r;
}
$json_string = json_encode($rows);
$json_string = str_replace("\\", "", $json_string, $i);
return $json_string;
} else {
return false;
}
}

$result = mysql_query($query) or die(mysql_error());
$resultNo = mysql_num_rows($result);
// check for successful store
if ($result != null) {
$rows = array();
while($r = mysql_fetch_assoc($result)) {
$rows[] = $r;
}
return json_encode($rows);
} else {
return false;
}
I think it's just your braces

What you are passing to JSONObject is in fact an array with a single object in it.
JSONObjectis expecting the syntax to be only representative of a single object containing key-value pairs (i.e. properties).
You need to not pass an array for this to work, or you need to use JSONArray to decode the JSON.

I had similar problem when I needed to pass json data from php to java app, this solved my problem:
$serialliazedParams = addslashes(json_encode($parameters));

You need to escape certain characters added by PHP, as well as substring your json string to cut out the additional characters at the front of the returned string.
One way to do it is like so:
ANDROID/JAVA code
JSONObject response = new JSONObject(responseString.substring(responseString.indexOf('{'),responseString.indexOf('}') +1).replace("\\",""));
You should do it a bit more neatly, but the point is that you have to ensure that the string you're passing in has no hidden characters, and to replace the first """ character with nothing as it can cause the exception.

Related

How to properly get JSONArray Items?

I have a php file where i retrieve data from a db, then convert it to an array, and then encode it, so the Android app I'm developing gets the JSONArray parse it, and get the data.
This is the php file:
<?php
$response = array();
// include db connect class
require_once __DIR__ . '/db_connect.php';
// connecting to db
$db = new DB_CONNECT();
$dbh = $db->connect(); // here you get the connection
$query = "SELECT *FROM lost_pets";
$result = $dbh->prepare($query);
$result->execute();
if ($result->fetchAll() > 0) {
foreach($dbh->query($query) as $row){
$pet["id"] = $row['id'];
$pet["name"] = $row['name'];
$pet["breed"] = $row['breed'];
$response["pet"] = array($pet);
echo json_encode($response);
}
}
?>
This is the result:
{"pet":[{"id":"1","name":"Prueba","breed":"Yorkshire Terrier"}]}{"pet":[{"id":"2","name":"Prueba2","breed":"German Shepherd"}]}{"pet":[{"id":"3","name":"Prueba3","breed":"Beagle"}]}
The problem is, when I retrieve the JSONObject in Android, and do getJSONArray(), instead of giving me 3 arrays i just get the above result.
I really don't have a very good understanding of PHP but following the php documentation I don't see what I am doing wrong.
I'm very close to finish the app, this is the only big problem I couldn't solve by now, and it is really upsetting me. Thanks!
EDIT:
JSONParser
else if(method.equals("GET")){
// request method is GET
if (sbParams.length() != 0) {
url += "?" + sbParams.toString();
}
try {
urlObj = new URL(url);
conn = (HttpURLConnection) urlObj.openConnection();
conn.setDoOutput(false);
conn.setRequestMethod("GET");
conn.setRequestProperty("Accept-Charset", charset);
conn.setConnectTimeout(15000);
conn.connect();
is = conn.getInputStream();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + '\n');
}
is.close();
json = sb.toString();
System.out.println(json.toString() + "This is the json");
} 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());
}catch (NullPointerException ex){
System.out.println("No internet");
}
return jObj;
}
conn.disconnect();
return jObj;
}
You need array_push where $pet pushed in array and print that array.
use,
<?php
$arr=array();
foreach($dbh->query($query) as $row){
$pet["id"] = $row['id'];
$pet["name"] = $row['name'];
$pet["breed"] = $row['breed'];
$response["pet"] = array_push($arr,$pet);
}
print_r($arr);
?>
You need to encode the final array structure once, encoding in your loop results in invalid json in the end as you will have multiple concatenated json strings.
The easiest way to get that, is to select only the fields you want:
$query = "SELECT id, name, breed FROM lost_pets";
$result = $dbh->prepare($query);
$result->execute();
echo json_encode($result->fetchAll(PDO::FETCH_ASSOC));
exit;
If you need a pet or pets key somewhere inbetween, you might need a loop but you can assign the rows at once just the same; no need to assign the individual fields.
I used below function in all my apps to get data from php & json arrays. Try this.
public void ParseJsonArray(json){ //json is the json array you got. pass it to this function. this can get specific data from json array.
try {
JSONArray jsonArray = json.getJSONArray("pet"); //get all data
int count = 0;
//if you have more columns & you want to get specific columns.
while (count<jsonArray.length()){
JSONObject JO = jsonArray.getJSONObject(count); //get data row by row.
String s1 = JO.getString("id"); //get id value to string s1.
String s2 = JO.getString("name"); //get name to string s2.
String s3 = JO.getString("breed"); //get breed to string s3.
count++; }
} catch (JSONException e) {
e.printStackTrace(); }
}

json encode array from php sql server and convert to Android

Hi i am new in android php client server. At present, i am doing the response from php sql server sending to Android client multiple result from sql row. Previously, i sending a simple string and receive android like below:
$result_data = array(
'ResultArray' => 'success',
);
#Output the JSON data
echo json_encode($result_data);
Then in android:
// Create a JSON object from the request response
JSONObject jsonObject = new JSONObject(result);
//Retrieve the data from the JSON object
String resultLoging = jsonObject.getString("ResultArray");
Now i want to receive from database having 3 columns: id, phone, name. How would i do that? Thank for your helping
use the following format in php
$result = mysql_query("SELECT *FROM tablename") or die(mysql_error());
// check for empty result
if (mysql_num_rows($result) > 0)
{
// looping through all results
// products node
$response["details"] = array();
while ($row = mysql_fetch_array($result))
{
// temp user array
$product = array();
$product["id"] = $row["id"];
$product["name"] = $row["name"];
array_push($response["details"], $product);
}
// success
$response["success"] = 1;
// echoing JSON response
echo json_encode($response);
In android
get success value
int success = json.getInt(TAG_SUCCESS);
get the datas using following format
JSONArray spi = json.getJSONArray("details");
Use a for loop to get the object values in the array
for (int i = 0; i < spi.length(); i++)
{
JSONObject c = spi.getJSONObject(i);
id = c.getString("id");
}
Use JSONArray for multiple json result :
JSONArray jsonArray = jsonObject.getJSONArray("ResultArray");
Iterate JSONArray and get value from JSONObject :
for (int i=0;i<jsonArray.length();i++){
JSONObject json = jsonArray.getJSONObject(i);
String id = json.getString("id");
String phone = json.getString("phone");
String name = json.getString("name");
}
just found this, would be the best for my question
https://stackoverflow.com/a/3563464/1345454
$results = array();
while($row = mysql_fetch_array($sql))
{
$results[] = array(
'title' => base64_decode($row['title']),
'price' => $row['price'],
'seller_user' => $row['user']
);
}
$json = json_encode($results);
try this
$result_data = array(
'ResultArray' => 'success',
);
echo json_encode(array('result'=>$result_data));
in android
JSONParser jParser = new JSONParser();
JSONObject json = jParser.getJSONFromUrl("url of php file");
JsonArray arry = json.getJSONArray("result");
JSONObject c = arry .getJSONObject(0);
String resultarr= c.getString("ResultArray");
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
// function get json from url
// by making HTTP POST or GET mehtod
public JSONObject makeHttpRequest(String url, String method,
List<NameValuePair> params) {
// Making HTTP request
try {
// check for request method
if(method == "POST"){
// request method is POST
// 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();
}else if(method == "GET"){
// request method is GET
DefaultHttpClient httpClient = new DefaultHttpClient();
String paramString = URLEncodedUtils.format(params, "utf-8");
url += "?" + paramString;
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
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) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
// System.out.println(json);
} 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;
}
}

I trying to send this json data form android to php server

I trying to send this json data form android to php server.
this my json data{email:"user111#gmail.com",password:"00000"},
any one help how the decode this json data in php server
this my php server code
<?php
$response = array();`
require_once __DIR__ . '/db_connect.php';`
if(!isset($_POST['params'])){
$decoded=json_decode($_POST['params'],true)
$email=json_decode['email'];
$pass=json_decode['password'];
// connecting to db
$db = new DB_CONNECT();`
$result = mysql_query("SELECT *FROM user WHERE email = $email");
if (!empty($result)) {
// check for empty result
if (mysql_num_rows($result) > 0) {`
$result = mysql_fetch_array($result);
$this->mylog("email".$email.",password".$pass);
if($pass==$result[password]){
echo " password is correct";
$response["code"]=0;
$response["message"]="sucess";
$response["user_id"]=$result["userid"];
$response["firstname"]=$result["fname"];
$response["lastname"]=$result["lname"];
echo json_encode($response);
}else{
$response["code"]=3;
$response["message"]="invalid password and email";
echo json_encode($response);
}
}else {
// required field is missing
$response["code"] = 1 ;
$response["message"] = "no data found";
// echoing JSON response
echo json_encode($response);
}
}
}else {
// required field is missing
$response["code"] = 0;
$response["message"] = "Required field(s) is missing";
// echoing JSON response
echo json_encode($response); }?>
**this my android code json praser **
public JSONObject loginUser(String email, String password) {
Uri.Builder loginURL2 = Uri.parse(web).buildUpon();
loginURL2.appendPath("ws_login.php");
JSONObject loginJSON = new JSONObject();
try {
loginJSON.put("email", email);
loginJSON.put("password", password);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
JSONObject json = jsonParser.getJSONFromUrl(loginURL2.toString(),
loginJSON);
return json;
}
this my android json data send function
public JSONObject getJSONFromUrl(String url, JSONObject params) {
// Making HTTP request
try {
// defaultHttpClient
// boolean status=isNetworkAvailable();
HttpParams param = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(param, 10000);
HttpConnectionParams.setSoTimeout(param, 10000);
DefaultHttpClient httpClient = new DefaultHttpClient(param);
HttpPost httpPost = new HttpPost(url);
StringEntity se = new StringEntity(params.toString());
se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE,
CONTENT_TYPE_JSON));
httpPost.setEntity(se);
Log.d("URL Request: ", url.toString());
Log.d("JSON Params: ", params.toString());
HttpResponse httpResponse = httpClient.execute(httpPost);
int code = httpResponse.getStatusLine().getStatusCode();
if (code != 200) {
Log.d("HTTP response code is:", Integer.toString(code));
return null;
} else {
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}
} catch (ConnectTimeoutException e) {
// TODO: handle exception
Log.e("Timeout Exception", e.toString());
return null;
} catch (SocketTimeoutException e) {
// TODO: handle exception
Log.e("Socket Time out", e.toString());
return null;
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
return null;
} catch (ClientProtocolException e) {
e.printStackTrace();
return null;
} catch (IOException e) {
e.printStackTrace();
return null;
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
jsonResp = sb.toString();
Log.d("Content: ", sb.toString());
} catch (Exception e) {
Log.e("Buffer Error", "Error converting Response " + e.toString());
return null;
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(jsonResp);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON Object
return jObj;
}
public boolean isNetworkAvailable(Context context) {
ConnectivityManager cm = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = cm.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnected()) {
return true;
}
return false;
}
If $_POST['params'] is a JSON encoded string, you only have to call json_decode once, not the multiple times that you have shown.
$decoded = json_decode($_POST['params'], true);
// Decoded is now an array of the JSON data
$email = $decoded['email'];
$pass = $decoded['password'];
It should be noted that the string in your question is not valid JSON, as email and password need to be quoted, as well.
You can do live testing of the json_decode function here:
http://php.fnlist.com/php/json_decode
You can validate your JSON here:
http://jsonlint.com

Sending and receiving json from android app to php script?

I am new to android development and I am trying to make a login page which sends the password and username to a php script as a json array and the php script returns a json array response which contains the meassage accordingly.
I have made a android code as:
jobj.put("uname", userName);
jobj.put("password", passWord);
JSONObject re = JSONParser.doPost(url, jobj);
Log.v("Received","Response received . . ."+re);
// Check your log cat for JSON reponse
Log.v("Response: ", re.toString());
int success = re.getInt("success");
if (success == 1) {
return 1;
}
else{
return 0;
}
}
catch(Exception e){ e.getMessage(); }
}
The JsonParser doPost code is as follows:
public static JSONObject doPost(String url, JSONObject c) throws ClientProtocolException, IOException
{
HttpClient httpclient = new DefaultHttpClient();
HttpPost request = new HttpPost(url);
HttpEntity entity;
StringEntity s = new StringEntity(c.toString());
s.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
entity = s;
request.setEntity(entity);
Log.v("entity",""+entity);
HttpResponse response;
try{
response = httpclient.execute(request);
Log.v("REceiving","Received . . .");
HttpEntity httpEntity = response.getEntity();
is = httpEntity.getContent();
Log.v("RESPONSE",""+is);
}
catch(Exception e){
Log.v("Error in response",""+e.getMessage());
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
Log.v("Reader",""+reader.readLine());
while ((line = reader.readLine()) != null) {
Log.v("line",""+line);
sb.append(line + "\n");
}
Log.v("builder",""+sb);
is.close();
json = sb.toString();
} catch (Exception e) {
Log.v("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.v("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
I have the php script as:
$response = array();
$con=mysqli_connect("localhost","uname","password","db_manage");
if((isset($_POST['uname']) && isset($_POST['password']))){
$empid = $_POST['uname'];
$pass = $_POST['password'];
$query = "SELECT mm_emp_id,mm_password FROM employee_master WHERE mm_emp_id='$empid'and mm_password='$pass'";
$result = mysqli_query($con, $query);
if(count($result) > 0){
$response["success"] = 1;
$response["message"] = "";
echo json_encode($response);
}
else{
$response["success"] = 0;
$response["message"] = "The username/password does not match";
echo json_encode($response);
}
}
I am getting undefined index at the line where I check for isset(). What am I doing wrong in receiving the json in php script?
If you can see I have used a link for my help
Please do help me out.
In the doPost method you don't use the JSON object (JSONobject c) that contains the variables
public class JSONTransmitter extends AsyncTask<JSONObject, JSONObject, JSONObject> {
String url = "http://test.myhodo.in/index.php/test/execute";
#Override
protected JSONObject doInBackground(JSONObject... data) {
JSONObject json = data[0];
HttpClient client = new DefaultHttpClient();
HttpConnectionParams.setConnectionTimeout(client.getParams(), 100000);
JSONObject jsonResponse = null;
HttpPost post = new HttpPost(url);
try {
StringEntity se = new StringEntity("json="+json.toString());
post.addHeader("content-type", "application/x-www-form-urlencoded");
post.setEntity(se);
HttpResponse response;
response = client.execute(post);
String resFromServer = org.apache.http.util.EntityUtils.toString(response.getEntity());
jsonResponse=new JSONObject(resFromServer);
Log.i("Response from server", jsonResponse.getString("msg"));
} catch (Exception e) { e.printStackTrace();}
return jsonResponse;
}
Main Activity
try {
JSONObject toSend = new JSONObject();
toSend.put("msg", "hello");
JSONTransmitter transmitter = new JSONTransmitter();
transmitter.execute(new JSONObject[] {toSend});
} catch (JSONException e) {
e.printStackTrace();
}

JSONException: Value of type java.lang.String cannot be converted to JSONObject

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 .
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.
I had a same problem. Maybe you need to save without unicode signature (BOM).

Categories