I have a JSON file with 2 JSON-Arrays in it:
One Array for routes and one Array for sights.
A route should consist of several sights where the user gets navigated to.
Unfortunately I am getting the error:
JSONException: Value of type java.lang.String cannot be converted to JSONObject
Here are my variables and the code that parses the JSON-File:
private InputStream is = null;
private String json = "";
private JSONObject jObj = 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();
// hier habe ich das JSON-File als String
json = sb.toString();
Log.i("JSON Parser", 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;
}
Log.i("JSON Parser", json);
shows me that at the beginning of the generated string there is a strange sign:
but the error happens here:
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
04-22 14:01:05.043: E/JSON Parser(5868): Error parsing data
org.json.JSONException: Value //STRANGE SIGN HERE // of type
java.lang.String cannot be converted to JSONObject
anybody has a clue on how to get rid of these signs in order to create the JSONObject?
Reason is some un-wanted characters was added when you compose the String.
The temp solution is
return new JSONObject(json.substring(json.indexOf("{"), json.lastIndexOf("}") + 1));
But try to remove hidden characters on source String.
see this
http://stleary.github.io/JSON-java/org/json/JSONObject.html#JSONObject-java.lang.String-
JSONObject
public JSONObject(java.lang.String source)
throws JSONException
Construct a JSONObject from a source JSON text string. This is the most commonly used` JSONObject constructor.
Parameters:
source - `A string beginning with { (left brace) and ending with } (right brace).`
Throws:
JSONException - If there is a syntax error in the source string or a duplicated key.
you try to use some thing like:
new JSONObject("{your string}")
Had the same problem for few days. Found a solution at last. The PHP server returned some unseen characters which you could not see in the LOG or in System.out.
So the solution was that i tried to substring my json String one by one and when i came to substring(3) the error went away.
BTW. i used UTF-8 encoding on both sides.
PHP side: header('Content-type=application/json; charset=utf-8');
JAVA side: BufferedReader reader = new BufferedReader(new InputStreamReader(is, "utf-8"), 8);
So try the solution one by one 1,2,3,4...! Hope it helps you guys!
try {
jObj = new JSONObject(json.substring(3));
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data [" + e.getMessage()+"] "+json);
}
This worked for me
json = json.replace("\\\"","'");
JSONObject jo = new JSONObject(json.substring(1,json.length()-1));
Here is UTF-8 version, with several exception handling:
static InputStream is = null;
static JSONObject jObj = null;
static String json = null;
static HttpResponse httpResponse = null;
public JSONObject getJSONFromUrl(String url) {
// Making HTTP request
try {
HttpParams params = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(params, 10000);
HttpConnectionParams.setSoTimeout(params, 10000);
HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);
HttpProtocolParams.setUseExpectContinue(params, true);
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient(params);
HttpGet httpPost = new HttpGet( url);
httpResponse = httpClient.execute( httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException ee) {
Log.i("UnsupportedEncodingException...", is.toString());
} catch (ClientProtocolException e) {
Log.i("ClientProtocolException...", is.toString());
} catch (IOException e) {
Log.i("IOException...", is.toString());
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "utf-8"), 8); //old charset iso-8859-1
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
reader.close();
json = sb.toString();
Log.i("StringBuilder...", 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 (Exception e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
try {
jObj = new JSONObject(json.substring(json.indexOf("{"), json.lastIndexOf("}") + 1));
} catch (Exception e0) {
Log.e("JSON Parser0", "Error parsing data [" + e0.getMessage()+"] "+json);
Log.e("JSON Parser0", "Error parsing data " + e0.toString());
try {
jObj = new JSONObject(json.substring(1));
} catch (Exception e1) {
Log.e("JSON Parser1", "Error parsing data [" + e1.getMessage()+"] "+json);
Log.e("JSON Parser1", "Error parsing data " + e1.toString());
try {
jObj = new JSONObject(json.substring(2));
} catch (Exception e2) {
Log.e("JSON Parser2", "Error parsing data [" + e2.getMessage()+"] "+json);
Log.e("JSON Parser2", "Error parsing data " + e2.toString());
try {
jObj = new JSONObject(json.substring(3));
} catch (Exception e3) {
Log.e("JSON Parser3", "Error parsing data [" + e3.getMessage()+"] "+json);
Log.e("JSON Parser3", "Error parsing data " + e3.toString());
}
}
}
}
}
// return JSON String
return jObj;
}
This is simple way (thanks Gson)
JsonParser parser = new JsonParser();
String retVal = parser.parse(param).getAsString();
https://gist.github.com/MustafaFerhan/25906d2be6ca109f61ce#file-evaluatejavascript-string-problem
I think the problem may be in the charset that you are trying to use. It is probably best to use UTF-8 instead of iso-8859-1.
Also open whatever file is being used for your InputStream and make sure no special characters were accidentally inserted. Sometimes you have to specifically tell your editor to display hidden / special characters.
return response;
After that get the response we need to parse this By:
JSONObject myObj=new JSONObject(response);
On response there is no need for double quotes.
I made this change and now it works for me.
//BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
BufferedReader reader = new BufferedReader(new InputStreamReader(is, HTTP.UTF_8), 8);
The 3 characters at the beginning of your json string correspond to Byte Order Mask (BOM), which is a sequence of Bytes to identify the file as UTF8 file.
Be sure that the file which sends the json is encoded with utf8 (no bom) encoding.
(I had the same issue, with TextWrangler editor. Use save as - utf8 (no bom) to force the right encoding.)
Hope it helps.
In my case the problem occured from php file.
It gave unwanted characters.That is why a json parsing problem occured.
Then I paste my php code in Notepad++ and select Encode in utf-8 without BOM
from Encoding tab and running this code-
My problem gone away.
In my case, my Android app uses Volley to make a POST call with an empty body to an API application hosted on Microsoft Azure.
The error was:
JSONException: Value <p>iisnode of type java.lang.String cannot be converted to JSONObject
This is a snippet on how I was constructing the Volley JSON request:
final JSONObject emptyJsonObject = new JSONObject();
JsonObjectRequest request = new JsonObjectRequest(Request.Method.POST, url, emptyJsonObject, listener, errorListener);
I solved my problem by creating the JSONObject with an empty JSON object as follows:
final JSONObject emptyJsonObject = new JSONObject("{}");
My solution is along the lines to this older answer.
if value of the Key is coming as String and you want to convert it to JSONObject,
First take your key.value into a String variable like
String data = yourResponse.yourKey;
then convert into JSONArray
JSONObject myObj=new JSONObject(data);
For me, I just needed to use getString() vs. getJSONObject() (the latter threw that error):
JSONObject jsonObject = new JSONObject(jsonString);
String valueIWanted = jsonObject.getString("access_token"))
Related
In my Android application, I need to send an array as body (payload information) to a POST url.
In body, there are two params:
1. "env" : "dev"
2. "dNumber" : tn("+1232323"); // here I need to send an array.
Edited question: I need to send phone as an array like ["123131","4545545"]
I pass the array as created a JSON array and convert to string and passed.
private String tn(String tn) {
String json = "";
try {
JSONArray jsonArray = new JSONArray();
jsonArray.put(0, tn);
json = jsonArray.toString();
} catch (JSONException e) {
e.printStackTrace();
}
return json;
}
and full code is:
try {
URL url;
HttpURLConnection urlConnection;
url = new URL(makeCallUrl);
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("POST");
urlConnection.setRequestProperty("Content-Type", "application/json");
urlConnection.setRequestProperty("Authorization", String.format("%s %s", "Basic", secretKey));
urlConnection.setUseCaches(false);
urlConnection.setDoOutput(true);
urlConnection.connect();
// Setup the body of the url
JSONObject json = new JSONObject();
json.put("env", "dev");
json.put("destNumbers", tn("+123123"));
// Write the body on the wire
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(urlConnection.getOutputStream()));
writer.write(json.toString());
writer.flush();
writer.close();
} catch (IOException e) {
Log.d(TAG, "IOException:" + e.getMessage());
e.printStackTrace();
}
If I try this, I got 400, Bad request exception.
Please help me to pass an array to POST api
I solved my problem using JSONArray and pass the array.
// creating json array
JSONArray numberArray = new JSONArray();
numberArray.put(0, tn);
// send the array with payload
JSONObject json = new JSONObject();
json.put("env", "DEV");
json.put("destNumbers", numberArray);
Now I get array as following:
destNumbers = ["3434343","3434334]
Update your tn() method. Instead of returning String it should return JSONArray.
private JSONArray tn(String tn) {
JSONArray jsonArray = new JSONArray();
try {
jsonArray.put(0, tn);
} catch (JSONException e) {
e.printStackTrace();
}
return jsonArray ;
}
Although if still the 400 Bad request error occur than confirm and verify the request payload with your json.
I am a new programmer, i am trying to build an app with Json.
I created Json parser class and in my main activity i have the following code :
String url = "http://echo.jsontest.com/key/value/one/two";
JSONObject json = jParser.getJSONFromUrl(url);
one = json.getString(gridArray.get(lekeres).getTitle()); // one has the good value "two"
This works great. BUT
if i change url to : https://api.myjson.com/bins/3f8d2
which is exactly the same code as in the jsontest, one doesn't have "two" . I searched for hours but i don't know why this is happening. I did nothing but change the url. The contest is the same...
Since I don't know how is your parser. I made a quick test and can read both link normally with this code:
try {
//url = new URL(""http://echo.jsontest.com/key/value/one/two2");
url = new URL("https://api.myjson.com/bins/3f8d2");
InputStream is = url.openStream();
JSONObject json = null;
BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));
StringBuilder sb = new StringBuilder();
int cp;
while ((cp = rd.read()) != -1) {
sb.append((char) cp);
}
String jsonText = sb.toString();
json = new JSONObject(jsonText);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
This is more examples: http://en.proft.me/2013/12/5/how-parse-json-java/.
You can make your getJSONFromUrl similarly. Otherwise like other suggest try without https://.
When downloading a JSON array, it cuts off 1/4 of the way through the string, its pretty huge - but it should get the entire string.
There are no errors thrown in the LogCat. This is the method I am using, I have been through it a few times and cant see a reason why it is cutting off. I am pretty new to this however.
public static JSONArray getJSONfromURL(String url){
//initialize
InputStream is = null;
String result = "";
JSONArray jArray = null;
//http post
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
} catch (Exception e) {
Log.e("log_tag", "Error in http connection "+e.toString());
}
//convert response to string
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();
result=sb.toString();
} catch (Exception e) {
Log.e("log_tag", "Error converting result "+e.toString());
}
//try parse the string to a JSON object
try {
Log.d("log_tag", "jresult: " + result + "finish");
jArray = new JSONArray(result);
//Log.e("log_tag", "result: " + jArray.toString());
} catch (JSONException e) {
Log.e("log_tag", "Error parsing data "+e.toString());
}
return jArray;
}
I think once this is cracked I will be set. I will make this a class to use in future projects too so I dont have to keep rebuilding it!
EDIT: For loop where markers should be added to map:
try{
for(int i=0;i<arrayResultFromURL.length();i++){
JSONObject json_data = arrayResultFromURL.getJSONObject(i);
// assign attributes from the JSON string to local variables
String id =json_data.getString("id");
String title =json_data.getString("title");
String strap =json_data.getString("strap");
Double lat = (double) json_data.getDouble("lat");
Double lon = (double) json_data.getDouble("long");
theMap.addMarker(new MarkerOptions()
.position(new LatLng(lat, lon))
.title(title)
.snippet(strap));
}
}catch (Exception e){
Log.e("log_tag", "error in array: " + e.toString());
}
Maybe your problem comes from the way your are treating the response object. Check this thread.
If not try to check the size of the response first to see if you are receving all.
httpResponse.getEntity().getContentLength()
Also just in case you didn't know there is a nice library (i've been using it since i found it) that simplifies json parsing ckeck it out here.
These type of things can best be done by libraries such as GSON or Jackson
Also, if your goal is to create a JSONArray, there is a constructor that takes in a JSONTokener. JSONTokener can in turn be constructed from your InputStream.
When I try to convert an HTTP POST response to JSONArray I get the error:
org.json.JSONException: Value of type java.lang.String cannot be converted to JSONArray
the error happens in the line: JSONArray jArray = new JSONArray(result);
the value of the string result is [{"return":"1"}] but it includes an extra blank character at the beginning that when removed, solves the problem. However, this character is not blank because a trim does not solve the problem. I believe there is some problem with the POST response, maybe badly constructed? (or maybe the POST request is wrong?) Any help is welcome.
A GET request works just fine, but I need to do a POST request.
This is the code:
HttpPost("usuarioLogin.php",nameValuePairs);
String result = ConvertResponseToString();
try{
JSONArray jArray = new JSONArray(result);
JSONObject json_data=null;
for(int i=0;i<jArray.length();i++){
json_data = jArray.getJSONObject(i);
ret = json_data.getInt("return");
retorno = (ret==1)?true:false;
}
}
catch(JSONException e1){
e1.printStackTrace();
} catch (ParseException e1) {
e1.printStackTrace();
}
this is the code of the function HttpPost()
private void HttpPost(String php, ArrayList<NameValuePair> nameValuePairs)
{
try{
HttpClient httpclient = new DefaultHttpClient();
String host = com.android.taggies.LoginUser.getContext().getResources().getString(R.string.host);
HttpPost httppost = new HttpPost("http://"+host+php);
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
}catch(Exception e){
Log.e("log_tag", "Error in http connection "+e.toString());
}
}
this is the code of the function ConvertResponseToString()
private String ConvertResponseToString()
{
//convert response to string
String result = null;
try{
//BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"utf-8"));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result=sb.toString();
}
catch(Exception e){
Log.e("log_tag", "Error converting result "+e.toString());
}
return result;
}
this is the code of my php that replies to the POST
<?php
mysql_connect("localhost","root","");
mysql_select_db("dbTaggies");
$q=mysql_query("SELECT count(*) as 'return' FROM users
WHERE name='$_POST[user]' AND password ='$_POST[pass]'");
while($e=mysql_fetch_assoc($q))
{
$output[]=$e;
}
print(json_encode($output));
mysql_close();
?>
I'm using this and for me always works fine:
DefaultHttpClient client = new DefaultHttpClient();
JSONObject json = null;
String resoult = "";
try
{
HttpPost postRequest = new HttpPost("XXXXXXXXXXXXXXXXXX");
HttpResponse postResponse = client.execute(postRequest);
HttpEntity postResponseEntity = postResponse.getEntity();
if (postResponseEntity != null)
resoult= EntityUtils.toString(postResponseEntity);
json = new JSONObject(resoult);
}
catch(Exception e)
{
}
The problem is solved.
PHP files were saved in UTF-8 WITH BOM, the solution was saving the files in UTF8 no BOM and the initial character in the POST response was removed.
I found a problem with some results of a search on a DB. When, some fields have extra characters like "ü", the field return as null so it appear as null on the search. My code is like this:
the php Script
$q=mysql_query("SELECT * FROM PRODFAR WHERE ARTI LIKE '%".$_REQUEST['search']."%'");
while($e=mysql_fetch_assoc($q))
$output[]=$e;
print(json_encode($output));
mysql_close();
the JSON PARSER constructor:
public class JsonParser {
static InputStream is = null;
static JSONObject json_data = null;
static String result = "";
// constructor
public JsonParser() {
}
public JSONArray getJSONFromUrl(ArrayList<NameValuePair> nameValuePairs, String url) {
//http post this will keep the same way as it was (it's important to do not forget to add Internet access to androidmanifest.xml
InputStream is = null;
String result ="";
JSONArray jArray = null;
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
}
catch(Exception e){
Log.e("log_tag", "Error in http connection "+e.toString());
}
//convert response that we receive from the php file into a String()
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();
result = sb.toString();
}catch(Exception e){
Log.e("log_tag", "Error converting result "+e.toString());
}
// try parse the string to a Json object
try {
//json_data = new JSONObject(result);
jArray = new JSONArray(result);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return Json String
return jArray;
}
}
any hint of how I can solve this?
update: as long as I cannot pass it with JSON, because it only admits UTF-8 characters. I think that one of the possible solutions is to convert the text through PHP into UTF-8 encoding archive, and the other is to use an alternative to JSON that supports other encodings. so I would like to try the first one. so if any know a good algorithm to covert the encoding of a text to UTF-8 using PHP will help to. Also other hints or tips of possible directions to find a solution are welcome please comment on this post any Idea is welcome
SOLVED
I solved it encoding it to UTF-8, it changed my characters like "ü" to something like u\000f, but the java editor show it as iso-8859-1 like Ü when it's showed on the screen. The edited PHP code have the following lines after the query:
$q=mysql_query("SELECT * FROM PRODFAR WHERE ARTI LIKE '%$search1%'");
while($e=mysql_fetch_assoc($q)){
$e['ARTI'] = utf8_encode ( $e['ARTI'] );
$e['DESC'] = utf8_encode ( $e['DESC'] );
$e['PRESENT'] = utf8_encode ( $e['PRESENT'] );
$output[]=$e;
}
print(json_encode($output));
JSON only support UTF8. So try using utf8_encode() / utf8_decode() for conversion.
At first blush, I'd guess it as an encoding issue. Make sure your tables are UTF-8 and also that your views are the same.
Also: Please don't put $_REQUEST data directly into your SQL. That will come back to haunt you.