dgallardo dgallardo - 4 months ago 17
JSON Question

JSONP- java String cannot be converted to JSONObject (Android)

That's my code:

String json = request.excutePost("http://192.168.1.42:3000/login_client",urlParameters);
JSONObject jsonObj = new JSONObject(json);


The logCat display me the next error:


org.json.JSONException: Value
{"login_client":"NEW_PASSWORD","token":"2de374f454699aa6fe895c56bc3a111b33f28b72888aec1f5faa77977e232828"}
of type java.lang.String cannot be converted to JSONObject


that's the executePost function:

public String excutePost(String targetURL, String urlParameters) {
HttpURLConnection connection = null;
try {

//Create connection
URL url = new URL(targetURL);
connection = (HttpURLConnection)url.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");

connection.setRequestProperty("Content-Length",
Integer.toString(urlParameters.getBytes().length));
connection.setRequestProperty("Content-Language", "en-US");

connection.setUseCaches(false);
connection.setDoOutput(true);

//Send request
DataOutputStream wr = new DataOutputStream (
connection.getOutputStream());
wr.writeBytes(urlParameters);
wr.close();
//Get Response
InputStream is = connection.getInputStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
StringBuilder response = new StringBuilder(); // or StringBuffer if not Java 5+
String line;

while((line = rd.readLine()) != null)
{
response.append(line);
response.append('\r');
}
rd.close();
//respuesta = response.toString().replaceAll("\"",);
Log.e("RESPONSE",response.toString());
return response.toString();
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
if(connection != null) {
connection.disconnect();
}
}
}

Answer

your problem is that your string has not been formatted well to convert. it should be some thing like this:

"{\"login_client\":\"NEW_PASSWORD\",\"token\":\"2de374f454699aa6fe895c56bc3a111b33f28b72888aec1f5faa77977e232828\"} "

try the code bellow:

import org.json.simple.JSONObject

String json =  request.excutePost("http://192.168.1.42:3000/login_client",urlParameters);
JSONObject obj = new JSONParser().parse(json).getAsJsonObject();

for more information take a look at this question : How to convert String to JSONObject in Java

Comments