java.lang.Integer cannot be converted to JSONObject - java

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

Related

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?

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

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

JSON parsing. Unexpected character (t) at position 2. JAVA

I'm trying to parse JSON data from a google maps search.
I've tryed both JACKSON and and now I'm Trying JSON SIMPLE. Both of them gives the same error.
First of all I'm doing an search on Google maps.
String urlString = "http://maps.google.com/maps?f=q&source=s_q&output=json&start=0&q="+ "Stockholm" + "+Gym";
Gives me JSON while(1);{title:"stockholm Gym - Google Maps",url:"/maps?f=q\x26source=s_q\x26start=0\x26q=stockholm+Gym\x26ie=UTF8\x26hq=Gym.............. and so on.
I'm replacing the while(1); with ""; before i return the string.
To the problem when I'm trying to parse it
JSONParser parser = new JSONParser();
String jsonString = "";
// UriHandler.mapSearchJson is the method that returns the jsonString.
String jsonData = UriHandler.mapSearchJSON(jsonString);
Object obj = "";
try {
obj = parser.parse(jsonData);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
JSONObject jsonObj = (JSONObject) obj;
String title = (String) jsonObj.get("title");
System.out.println(title);
This gives me the exception.
Unexpected character (t) at position 2.
When I'm debbuging it. comes all the way to when it's trying to parse the string. then the obj is = null.
What in thw world am I doing wrong.
Thanks!
As the others already mentioned, a nonquoted field name is not standard JSON. However, Jackson (and maybe others) has a set of option settings that allow it to work with nonstandard, but common JSON derivatives:
JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES
will enable processing of unquoted field names.
The response is not valid JSON, as the key name was not quoted with double quotes.
{title:"stockholm Gym"
is invalid JSON, it should be this:
{"title":"stockholm Gym"
Notice how title is surrounded by " double quotes
You are pulling back Javascript code that is meant for the maps.google.com site to use.
There could be any Javascript code in that response, not just the JSON that happens to be returned as part of the search.
You need to request from their maps API instead:
http://maps.googleapis.com/maps/api/geocode/json?address=Stockholm+Gym&sensor=false
This will return you only the JSON data.
Have a look the Google Maps API for more options.
I faced this error when trying to parse the json returned from kafka (kafka twitter producer).
The message returned was including some extra text other than json (KeyedMessage(twitter-test_english,null,null). Because of that I was facing this error.
KeyedMessage(twitter-test_english,null,null,{"created_at":"Sat Apr 23 18:31:10 +0000 2016","id":723942306777337856,"id_str":"723942306777337856"}
Pass only the message part from returned json and convert it into string.
{"created_at":"Sat Apr 23 18:31:10 +0000 2016","id":723942306777337856,"id_str":"723942306777337856"}
message = new KeyedMessage("twitter-test_english", (String)queue.take());
//System.out.println("This is message"+message.message());
String message_string = message.message().toString();
JsonParse.toParseJson(message_string);

Categories

Resources