I am using json_encode
to create JSON string in PHP. $result
is my SQL result.
$final_op="";
if(empty($result) == false){
$rows = array();
while($r = mysqli_fetch_assoc($result)) {
$rows[] = $r;
}
$final_op=json_encode($rows);
}
when I get this json string at the client end I get it like
[{"username":"vikasdevde","user_fname":"Vikas Devde","user_work":"Programmer"}]
And I am parsing it in Java as below
try{
JSONObject jObject = new JSONObject(response);
String aJsonUsername = jObject.getString("username");
String aJsonFname = jObject.getString("user_fname");
String aJsonUserWork = jObject.getString("user_work");
}catch(JSONException e){
e.printStackTrace();
System.out.println("JSON Exception");
}
But I'm getting a JSONException, may be it is because of the square brackets around, because after some research I tried with hard-coded string
"{\"username\":\"vikasdevde\",\"user_fname\":\"Vikas Devde\",\"user_work\":\"Programmer\"}"
and it worked. Could you please let me know what should be the best way to handle this?
That is the right way to go.