I have am trying to convert my response from a POST to JSON. And here is what I am doing:
InputStream is = connection.getInputStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
String line;
StringBuilder response = new StringBuilder();
while((line = rd.readLine()) != null) {
response.append(line).append("\r");
}
rd.close();
Log.i(TAG, response.toString());
JSONObject jsonObject = new JSONObject(response.toString());
But then I get error java.lang.String cannot be converted to JSONObject
But if I make a string, String string; and then I paste the what I logged and set it equal to string, and then try
JSONObject jsonObject = new JSONObject(string);
It works, so why is it working when I paste the logged response, but not when I just use response.toString();?
In the logcat it looks like this {"url": "www.google.com"}. And then when I paste it into string = "{\"url\": \"www.google.com\"}";
Thanks for the help
I met this problem before, try this:
new JSONObject(json.substring(json.indexOf("{"), json.lastIndexOf("}") + 1));
or
if (response != null && response.startsWith("\ufeff")) {
in = in.substring(1);
}
the response from server contains a BOM header
public JSONObject(java.lang.String source)
throws JSONException
Construct a JSONObject from a source JSON text string.
source - A string beginning with { (left brace) and ending with } (right brace).
So while doing response.toString() if the string do not start with { and close with } then it will throw Exception.
Related
I have a URL that retuns a JSON back and I first convert it to String and then convert it to JSONArray but for some reason, it's returning null.
The sample url looks like this:
https://data.phila.gov/resource/sspu-uyfa.json?dispatch_date=2017-08-01
Below is my code:
public JSONArray getJsonFromUrl(final String data_url) throws IOException, JSONException {
InputStream is = new URL(data_url).openStream();
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);
}
is.close();
JSONArray jsonArray = new JSONArray(sb.toString());
return jsonArray;
}
So the StringBuilder object sb is not null. When I debug, I can see it is a huge string. But it's new JSON(sb.toString()); that returns null. Also, I tried replacing JSONArray with JSONObject and still same issue.
Any help would be appreciated!
your data has a SyntaxError. in near column 48697,
H have find the bad data segment:
,"ucr_gen1447C3FA9C2915241",
I think you would like :
,"ucr_general":"1447C3FA9C2915241",
I am trying to register a user to my Web Server. If i send valid details to the server then i get 201 code in response which stands for "created". But when i send wrong credentials to the server i.e same username as before then i get 400 FileNotFoundException. I need to interpret error details not only 400 code. Because if i send wrong details using curl from command line then i get error details also e.g this username already exists.
Here is my code to read response from the server. Actually i've tried two different methods but they all end up in same error which is 400(Bad Request) nothing else.
public static String readResponse(HttpURLConnection connection)
throws IOException, JSONException {
InputStream is = connection.getInputStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
String line;
StringBuilder response = new StringBuilder();
while((line = rd.readLine()) != null) {
response.append(line);
response.append('\r');
}
return response.toString();
}
public static String readResponseFromServer(HttpURLConnection connection) throws IOException {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader
(connection.getInputStream()));
String line = "";
StringBuilder stringBuilder = new StringBuilder();
while ((line = bufferedReader.readLine()) != null) {
stringBuilder.append(line).append("\n");
}
return stringBuilder.toString();
}
In the above code there are two methods for reading response from the server.
And here is how i am using these methods to read response from the server
System.out.println("Server Response" + WebServiceHelpers.readResponseFromServer(urlConnection));
And i am also using the 2nd method which is readResponse() from the above code.
And here is the screenshot of curl command in which i am sending wrong details to the server and getting error details.
I've also tried this with HTTPIE and i am also getting the same response as using curl command i.e A user with that username already exists.
I need these error details in my Java code also. I have searched the internet but didn't found a solution.
Any suggestions?
Try this
public static String readResponse(HttpURLConnection connection)
throws IOException, JSONException {
int respCode = connection.getResponseCode();
InputStream is = null;
if (isErrorCode(respCode)) {
is = connection.getErrorStream();
} else if (connection.getErrorStream() != null) {
is = connection.getInputStream();
}
//FIXME: InputStreamReader must be constructed with right charset
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
String line;
StringBuilder response = new StringBuilder();
while((line = rd.readLine()) != null) {
response.append(line);
}
return response.toString();
}
Write isErrorCode method. It should interpret response code 400 as error and other codes as you need. Also notice fixme comment. When you are constructing InputStreamReader without a charset it uses default charset (UTF-8 if you don't provide file.encoding property) but correct way is to get charset from Content-Type response header and process response body with that encoding. Method for extracting charset from response may looks like this
private String getCharset(HttpURLConnection con) {
String charset = "";
String contentType = con.getContentType();
if (contentType != null) {
String[] values = contentType.split(";");
for (String value : values) {
String trimValue = value.trim();
if (trimValue.toLowerCase().startsWith("charset=")) {
charset = trimValue.substring("charset=".length());
}
}
}
if ("".equals(charset)) {
charset = "UTF-8";
}
return charset;
}
I am having some issues while parsing JSON response in Android. The response I get is:
{
"response": "{\"session_token\":\"48500d8e42acc09aa45cb8f3a7ba2b30\",\"user_login\":\"newoff2\",\"user_id\":\"62\",\"user_profile_img\":\"http://onepgr.com/system/photos/62/medium/userfile054c35e29.png?1422089771\",\"success\":\"0\",\"user_email\":\"newoff2#pdmoffice.com\"}"
}
I need the values for user_login, success, user_profile_img, user_email. Here is what I tried so far, but it won't do what I need:
HttpResponse response = httpClient.execute(httpPost);
// write response to log
Log.d("Http Post Response:", response.toString());
BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
String json = reader.readLine();
Log.d("Final Response",json);
jsonObject = new JSONObject(json);
JSONObject json1=jsonObject.getJSONObject("response");
String str = json1.getString("success");
Log.e("Parsed data is",str);
use this
json=json.replace("\\\"", "\"");
Log.e("resule",json);
try {
JSONObject jsonObject = new JSONObject(json);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
you can use regex to make your string JSON parsable
var res = data.replace(/\\"/g, '').replace(/\"{/g, '{').replace(/\}"/g, '}');
var jsonData = JSON.parse(res);
alert(jsonData.response.user_login);
Here is FIDDLE
Note: in fiddle I have declared your JSON with a ' ' to make it complete string
Use Scanner to remove \:
String resultStr = new Scanner(json).useDelimiter("\\A").next();
jsonObject = new JSONObject(resultStr);
Above is used for BufferedInputStream to get JSON string.
[UPDATE:]
For BufferReader, need to use StringBuilder to get JSON string:
StringBuilder strBuilder = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
strBuilder.append(line);
}
//for your JSON string, should use 'JSONTokener' to parse
jsonObject = (JSONObject) new JSONTokener(strBuilder.toString()).nextValue();
JSONObject json1=jsonObject.getJSONObject("response");
String str = json1.getString("success");
This should work for your case!
Try this....
InputStream inputStream = null;
String result = null;
try {
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
inputStream = entity.getContent();
// json is UTF-8 by default
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
result = sb.toString();
Log.d("Result",result);
JSONObject jsonObject = new JSONObject(result);
String resJson=jsonObject.getString("response");
Log.d("Result",resJson);
JSONObject jsparam=new JSONObject(resJson);
String success=jsparam.getString("success");
Log.d("Value for success",success);
// JSONObject json1=jsonObject.getJSONObject("response");
//String objResponse = json1.getString("success");
} catch (Exception e) {
// Oops
}
finally {
try{if(inputStream != null)inputStream.close();}catch(Exception squish){}
}
I really can't see where I'm going wrong with this. Any help would be much appreciated.
I have a JSONArray
JSONArray jsonArray = new JSONArray(responseString);
Where responseString is ["prob", "2"]
I get the 1st String
String maybeProb = jsonArray.getString(0);
and when I show it using a Toast all is ok and the toast popup just says prob
Toast.makeText(getBaseContext(),maybeProb ,Toast.LENGTH_LONG).show();
But when I use an if (maybeProb == "prob") it doesnt return true
Why not??? What am I doing wrong???
Some more details for you:
responseString which forms the original JSONArray comes from an HttpPost to my server
InputStream is = null;
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
//Convert response to string
responseString = convertStreamToString(is);
public String convertStreamToString(InputStream inputStream) {
StringBuilder sb = null;
String result = null;
try
{
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream,"UTF-8"));
sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
inputStream.close();
result = sb.toString();
}
catch(Exception e)
{
Toast.makeText(getBaseContext(),e.toString() ,Toast.LENGTH_LONG).show();
}
// return the string
return result;
}
The PHP on my server which makes the response is
$message = array("prob", "2");
$response = json_encode($message);
print($response);
Many thanks to anyone that can help me
To compare objects in java use .equals() method instead of "==" operator
Replace the following code
if(maybeProb == "prob") {
}
with this one.
if(maybeProb.equals("prob")) {
}
The equals operator (==) returns true only if both objects are the same, not if their value is the same. Therefore, when you compare the object maybeProb with the object "prob" it returns false
If you want to do the comparison, you have to use maybeprob.equals("prob").
Im using the following code to convert from a well-formed-String to a JSONObject in Java:
public void getStatus(){
String status = "";
try{
String line;
StringBuilder result = new StringBuilder("");
HttpURLConnection conn;
URL url;
url = new URL("http://bromio.com.mx/explore/PointOfInterestService.svc/GetData");
BufferedReader rd;
conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
while ((line = rd.readLine()) != null) {
result.append(line);
}
rd.close();
Log.d("JSON: ", result.toString());
JSONObject jsonObject = new JSONObject(result.toString());
}catch (Exception e){
e.printStackTrace();
}
}
But it's throwing an exception, it seems that i cannot cast that specific string to JSONObject.
The JSON can be acceses in this page: (It's too big to show!) http://bromio.com.mx/explore/PointOfInterestService.svc/GetData
Any help solving this problem will help me a lot. thank you
Let's take the first few characters of your json
"{ \"poi\":[\u000d\u000a
^ ^ ^ ^^^^^^
| | | |-----------> not sure about all this
| | -------------------> not acceptable in json
| ------------------------> not acceptable in json
---------------------------> not acceptable in json
What you get back from that website is not valid root json. Fix your source if you have control over it. Or use the String utility methods to replace those characters.