Error parsing JSON Object from PHP web service - java

I seem to be getting an incomplete JSON object from my PHP web service. My PHP codes are as follows:
<?php
define('IEM_PATH', '../admin/com');
require_once('../admin/includes/config.php');
require_once('../admin/com/lib/IEM.class.php');
require_once ('../admin/com/lib/IEM/DBFACTORY.class.php');
require_once ('../admin/com/lib/IEM/baseAPI.class.php');
require_once ('../admin/com/lib/API/USERS.class.php');
require_once ('../admin/com/lib/IEM/baseRecord.class.php');
require_once ('../admin/com/lib/record/Users.class.php');
function GetLists($userid = 0, $getUnconfirmedCount = false) {
$userid = $_REQUEST['userID'];
if (!$userid) {
trigger_error('User object has no user id as parameter.', E_USER_NOTICE);
return false;
}
if (!$userid) {
$userid = $this->userid;
}
require_once('../admin/functions/api/lists.php');
$listapi = new Lists_API();
$returnA = $listapi->GetListByUserID($userid, $getUnconfirmedCount);
$returnResult1 = array();
foreach ($returnA as $key => $value) {
//$lists[] = $key;
$returnResult["contactList"][] = array("listID" => $returnA[$key]['listid'], "name" => $returnA[$key]['name']);
}
$returnResult["success"] = 1;
echo json_encode($returnResult);
}
GetLists();
However when I try to retrieve the results my logcat only shows:
E/JSON Parser: Error parsing data org.json.JSONException: Value <br of type java.lang.String cannot be converted to JSONObject
W/System.err: org.json.JSONException: No value for success
By doing a logging, my android returns my JSON object as follows
D/Returned JSON: {"androidid":"1"}
from these codes
// getting JSON response from PHP web service
JSONObject returnedJSONObj = listsJSONParser.makeHttpRequest(Constant.URL
+ "RetrieveList.php", "GET", params);
Log.d("Returned JSON ", String.valueOf(returnedJSONObj));
success = returnedJSONObj.getInt("success");
I don't understand why there is no value for success when my PHP does return a JSON Array as well as the success value according to the code, but the android studio java codes does not detect these values in the JSON object. What am I doing wrong here?

you should modify your android code
success = returnedJSONObj.getInt("success");
to
success = returnedJSONObj.getInt("androidid");

The problem is that there is a problem with your php file, so instead of returning a JSON object, it returns a string with the error.
You need to make sure you are sending the correct POST or GET values to the URL if you are or you check for database errors. try logging the inputstream coming from the php server to see the full error it is sending

Related

retrofit get boolean from mysql

I have a problem with retrofit in my android app (java) retrieving a boolean field from php/mysql webservice.
In my java model, I have a boolean field selected, declared as:
#SerializedName("selected")
#Expose
private boolean selected;
In my MySQL database, the field is declared as TINYINT
When I upload my object, it is correctly saved in the database (0 or 1).
But when I want to download the same object, I get an error:
com.google.gson.JsonSyntaxException: java.lang.IllegalStateException:
Expected a boolean but was NUMBER at line 11 column 22 path
$[0].selected
php code:
<?php
header('content-type:application/json');
if (isset($_GET['deviceName']) && $_GET['deviceName'] != "") {
$deviceName = $_GET['deviceName'];
$sql = "SELECT * FROM `ComList` WHERE deviceName = '$deviceName' ORDER BY clistId, ord, categOrd ASC;";
$pdo_options[PDO::ATTR_ERRMODE] = PDO::ERRMODE_EXCEPTION;
$pdo_options[PDO::MYSQL_ATTR_INIT_COMMAND] = 'SET NAMES utf8';
$bdd = new PDO('mysql:host=localhost;dbname=bdd', 'user', 'password', $pdo_options);
$bdd->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$bdd->setAttribute(PDO::ATTR_STRINGIFY_FETCHES, false);
$response = $bdd->query($sql);
$output = $response->fetchAll(PDO::FETCH_ASSOC);
echo(json_encode($output, JSON_PRETTY_PRINT));
?>
I can't modify the type of the field in the java model.
Any idea please?
Something to modify in the SQL request?
Modify the output in PHP?
The only way I found that give a good result is:
$output = $response->fetchAll(PDO::FETCH_ASSOC);
$tab = array();
foreach($output AS $value) {
$value['selected'] = $value['selected'] ? true : false;
array_push($tab, $value);
}
echo(json_encode($tab, JSON_PRETTY_PRINT));
But I think it's such a dirty process.

com.google.gson.stream.MalformedJsonException

I am trying to upload image to local server using retrofit. Below is my php code.
<?php
require 'init.php';
if ($con) {
$title = $_POST['title'];
$image = $_POST['image'];
$upload_path = "uploads/$title.jpg";
$sql = "insert into imageinfo(title,path) values('$title', '$upload_path');";
if (mysqli_query($con, $sql)) {
file_put_contents($upload_path, base64_decode($image));
echo json_encode(array('response' => "Image uploaded successfully."));
} else {
echo json_encode(array('response' => "Error! Image is not uploaded."));
}
mysqli_close($con);
}
?>
But I am getting an error like this : com.google.gson.stream.MalformedJsonException Use JsonReader.setLenient(true) to accept malformed JSON at line 1 column 1 path $.
Then I added the following code in the class where retrofit is initialized.
Gson gson = new GsonBuilder().setLenient().create();
retrofit = new Retrofit.Builder().baseUrl(BASE_URL).addConverterFactory(GsonConverterFactory.create(gson)).build();
Now I am getting the following error : com.google.gson.JsonSyntaxException: java.lang.illegalStateException: Expected BEGIN_OBJECT but was STRING at line 1 column 1 path $
Whats wrong there? Is there anything wrong in php code?
Gson gson = new GsonBuilder().setLenient(true).create();
Try this.

How to extract data from a JSON array to variables and pass variables to a PHP function

I have a Java Program that sends a HTTP POST request to a PHP file. I need the PHP script to extract the JSON data to some variables and call a PHP function with those variables (parameters). Please find the PHP code below.
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST')
{
$data = json_decode(file_get_contents("php://input"), true);
var_export($data);
}
else
{
var_export($_SERVER['REQUEST_METHOD']);
}
?>
The JSON Object created in Java
JSONObject json = new JSONObject();
json.put("name", "Dash");
json.put("num", new Integer(100));
json.put("balance", new Double(1000.21));
Please help me understand how to extract the JSON array data to variables And how to make the call.
Once you've run json_decode(), $data is just a "normal" php array with "normal" php values in it.
So, e.g.
/*
JSONObject json = new JSONObject();
json.put("name", "Dash");
json.put("num", new Integer(100));
json.put("balance", new Double(1000.21));
=>
*/
// $input = file_get_contents("php://input");
$input = '{"name":"Dash","num":100,"balance":1000.21}';
$data = json_decode($input, true);
$response = array(
'name_rev' => strrev($data['name']),
'num_mod_17' => $data['num'] % 17,
'balance_mul_2' => $data['balance'] * 2
);
echo json_encode($response, JSON_PRETTY_PRINT); // you might want to get rid off JSON_PRETTY_PRINT in production code
prints
{
"name_rev": "hsaD",
"num_mod_17": 15,
"balance_mul_2": 2000.42
}
two more tips:
You should test whether $data contains all the elements you expect, before accessing them, see http://docs.php.net/isset , http://docs.php.net/filter et al
a java Double() called balance. A java double is a 64-bit IEEE 754 floating point. And you might hit at one point (if not the range than) the precision limit, see What is the best data type to use for money in java app?

java.lang.Integer cannot be converted to JSONObject

I am fetching status from PHP in JSON format, but always getting:
org.json.JSONException: Value 43 of type java.lang.Integer cannot be converted to JSONObject
My way of reading result from JSON
int strUserID;
......
strUserID = jsonObject.getInt("UserID");
And in php i am using:
$user_id = mysql_insert_id();
echo $user_id;
if(!$objQuery)
{
$arr['StatusID'] = "0"; // unable to create user
}
else
{
$arr['StatusID'] = "1"; // user created successfully
$arr['UserID'] = $user_id; // passing user id to android app
}
JSON sample on web:
46{"StatusID":"1","UserID":46}
But on Android side not getting data into json format, because facing exception
may i know where i am doing mistake ?
While returning the data from PHP you should encode it in JSON.
use below function
echo json_encode($arr);
In your php file remove
echo $user_id;
and use this after your else condition
echo json_encode($arr);

JSONP PHP Array Empty

im trying to get data via JSONP from my Webpage with a php script :
//connection and query above
...
while($r=mysqli_fetch_array($result)){
//Add the fetched vale to $json array
$json[] = $r;
// Content type
header("Content-type: application/json");
echo "$callback({email: 'Message from Server.php'});";
}
// Content type
header("Content-type: application/json");
//JSONP - Make it as JSONP object
echo $_GET['callback']."(".json_encode($json).")";
my echo "$callback({email: 'Message from Server.php'});"; <--- works
but my
echo $_GET['callback']."(".json_encode($json).")"; <--- returns null
when i call the script on my webpage like "page/callback.php"
i get following outputs in my Browser :
({email: 'Message from Server.php'});([{"0":"3","ID":"3","1":"dome","username":"dome","2":"vjvhrOWZYTq3qbrYfoE13A==","passwort":"vjvhrOWZYTq3qbrYfoE13A==","3":"mii#googlemail.com","email":"mii#googlemail.com","4":"0","active":"0","5":"hu","loc":"hu"}]
)
It contains -> "[" and "]"
my Java script is GWT :
JsonpRequestBuilder jsonp = new JsonpRequestBuilder();
jsonp.requestObject(URL.encode("http://webpage/callback.php?callback=test_clbk"), new AsyncCallback<JSONreceiver>() {
public void onFailure(Throwable throwable) {
System.out.println(throwable.getMessage());
}
#SuppressWarnings("unused")
public void onSuccess(JSONreceiver result) {
System.out.println(result.getResult());
}
});
You still do not have any answer.
Here is one solution :
1) Remove EVERY SINGLE echo / print / var_dump.
2) Initiate the json class with a callback
3) Forge your JSON with Simple JSON for PHP
4) Send your json at the end of the file
The results :
<?php
include('../includes/json.php');
// Set a callback
$json = new json('callback', 'mycallback');
// Forge your data
$json->add('email', 'message sent from Server.php');
while($r=mysqli_fetch_array($result)){
$answer[] = $r;
}
// Forge your data
$json->add('data', $answer);
$json->add('status', '200');
// Send
$json->send();
?>

Categories

Resources