com.google.gson.stream.MalformedJsonException - java

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.

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.

org.json.JSONException: JSONObject["minutes"] not found

This is my JSON object and I am trying to access the minutes from this JSON object but unable to access it, I have also tried writing some code, can anyone please help.
{"summary":"B.Com; LL.B.(Hons.) 5-Year integrated-MIBCBT802R01","recurrence":["RRULE:FREQ=DAILY;COUNT=1"],"reminders":{"overrides":[{"method":"email","minutes":1440}],"useDefault":"false"},"attendees":["qatest1#dc01.tcs-itontap.com"],"start":{"dateTime":"2022-10-24T08:40:00+05:30","timeZone":"India+5:30"},"description":"Lecture scheduled for Subject:Down Stream Processing Lab II and Activity: Practical","location":"India","end":{"dateTime":"2022-10-24T09:30:00+05:30","timeZone":"India+5:30"},"id":2300036}
```String remMinutes = new org.json.JSONObject(new org.json.JSONObject(jsonFromSolJSON.getJSONObject("reminders")).getJSONArray("overrides").getJSONObject(0)).getInt("minutes")```
Err - JSONError:: org.json.JSONException: JSONObject["minutes"] not found.
This could be one of the solution
var jsonObject = new JSONObject(json);
var result = jsonObject.getJSONObject("reminders").getJSONArray("overrides");
var minutes = result.getJSONObject(0).get("minutes");

JSONArray getting error

org.json.JSONException: Value [{"id":"98747406","name":"adam","surname":"hfdd","age":"2","latitude":"54.2118","longitude":"16.1876","origin":"koszalin","destination":"sian\u00f3w","ride_id":"262243421","date":"2017-05-25 18:13:00"}] at jaPassengers of type java.lang.String cannot be converted to JSONArray
Have anyone idea what cause this error? It occur when I try getJSONArray from server output e.g.:
output:
{"iActualJoinRequests":"4","jaPassengers":"[{\"id\":\"98747406\",\"name\":\"adam\",\"surname\":\"hfdd\",\"age\":\"2\",\"latitude\":\"54.2113448\",\"longitude\":\"16.1876282\",\"origin\":\"koszalin\",\"destination\":\"sian\u00f3w\",\"ride_id\":\"262243421\",\"date\":\"2017-05-25
18:13:00\"}]"}
JSONObject joOutput = new JSONObject(output);
JSONArray jaPassengers = joOutput.getJSONArray("jaPassengers");
EDIT: Problem solved, solution in comment.
If you used a json parser, the error would become pretty clear:
"jaPassengers" : "[{\"id\":\"98747406\",\"name\":\"adam\",\"surname\":\"hfdd\",\"age\":\"2\",\"latitude\":\"54.2113448\",\"longitude\":\"16.1876282\",\"origin\":\"koszalin\",\"destination\":\"sian\u00f3w\",\"ride_id\":\"262243421\",\"date\":\"2017-05-25 18:13:00\"}]"
Your array is actually encoded as a string.
To parse this, first fetch it as a string, then parse the resulting string as a JSONArray:
JSONObject joOutput = new JSONObject(output);
String makeShiftArray = joOutput.getString("jaPassengers");
JSONArray jaPassengers = new JSONArray(makeShiftArray);
It would be better to fix this on the server side if possible
Matt Clark, like you advised I'm trying to fix problem on server side. Code:
$aOutput = array('iActualJoinRequests' => $iActualJoinRequests, 'jaPassengers' => $aPassengers);
$joOutput = json_encode($aOutput, JSON_FORCE_OBJECT);
echo $joOutput;
cause error in java when I try to get JSONArray jaPassengers, but:
$aOutput = array('iActualJoinRequests' => $iActualJoinRequests, 'jaPassengers' => '');
$joOutput = json_encode($aOutput, JSON_FORCE_OBJECT);
$joOutput = json_decode($joOutput);
$joOutput -> jaPassengers = $aPassengers;
$joOutput = json_encode($joOutput);
echo $joOutput;
works :)
Problem solved.

Error parsing JSON Object from PHP web service

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

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);

Categories

Resources