This question already has answers here:
JSONException: Value of type java.lang.String cannot be converted to JSONObject
(14 answers)
Closed 8 years ago.
I know this exception is asked a million times before and I saw various post saying different suggestion and nothing worked for me yet.
I need to get some data from a url using httpget am giving a specific id along my url.
my output should looks likes this
{
"id": "35ZGXU7WQHFYY5BFTV6EACGEUS",
"createTime": "2014-04-11T12:52:26",
"updateTime": "2014-04-11T12:52:55",
"status": "Completed",
"transaction": {
"amount": {
"currencyCode": "GBP",
"total": 7.47
},
"qrcode": "189e8dad99908745o7439f8ffabdfipp",
"description": "This is the payment transaction description."
}
}
but due to something am getting this error
04-11 18:24:14.655: E/STATUS_ERR(30067): org.json.JSONException: Value com.mywallet.android.rest.MyWalletRestService$getStatus#41837fd0 of type java.lang.String cannot be converted to JSONObject
my code is as below
String line = null;
try{
BufferedReader in = null;
HttpGet request = new HttpGet();
URI website = new URI(url);
request.setURI(website);
request.setHeader("Accept", "application/json");
request.setHeader(AppConstants.PAYMENT_HEADER1, BEARER);
request.setHeader(AppConstants.content_type, AppConstants.application_json);
response = httpClient.execute(request);
in = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
while ((line = in.readLine()) != null)
{
sb.append(line + "\n");
}
result = sb.toString();
JSONObject jObject = new JSONObject(toReturn);
}
if(jObject.has("error")){
RES_STATUS = AppConstants.FAIL;
}
else{
AppVariables.id = jObject.getString(AppVariables.id_);
AppVariables.createTime = jObject.getString(AppVariables.createTime_);
AppVariables.updateTime = jObject.getString(AppVariables.updateTime_);
AppVariables.status = jObject.getString(AppVariables.status_);
JSONObject oneObject = jObject.getJSONObject("transaction");
JSONObject twoObject = oneObject.getJSONObject("amount");
AppVariables.total = twoObject.getString("total");
AppVariables.currencyCode = twoObject.getString("currencyCode");
AppVariables.qrcode = oneObject.getString(AppVariables.qrcode_);
AppVariables.description = oneObject.getString(AppVariables.description_);
MWLog.e("AppVariables.id", AppVariables.id);
MWLog.e("AppVariables.createTime", AppVariables.createTime);
MWLog.e("AppVariables.updateTime", AppVariables.updateTime);
MWLog.e("AppVariables.status", AppVariables.status);
MWLog.e("AppVariables.currencyCode", AppVariables.currencyCode);
MWLog.e("AppVariables.total", AppVariables.total);
MWLog.e("AppVariables.qrcode", AppVariables.qrcode);
MWLog.e("AppVariables.des", AppVariables.description);
RES_STATUS = AppConstants.SUCCESS;
MWLog.e("BUYER", toReturn);
}
Use this function to get proper json response
public String getResponseBody(final HttpEntity entity) throws IOException, ParseException {
if (entity == null) {
throw new IllegalArgumentException("HTTP entity may not be null");
}
InputStream instream = entity.getContent();
if (instream == null) {
return "";
}
if (entity.getContentLength() > Integer.MAX_VALUE) {
throw new IllegalArgumentException(
"HTTP entity too large to be buffered in memory");
}
StringBuilder buffer = new StringBuilder();
BufferedReader reader = new BufferedReader(new InputStreamReader(instream, HTTP.UTF_8));
String line = null;
try {
while ((line = reader.readLine()) != null) {
buffer.append(line.trim());
}
} finally {
instream.close();
reader.close();
}
return buffer.toString().trim();
}
How to use?
result= getResponseBody(response.getEntity());
result = sb.toString();
JSONObject jObject = new JSONObject(toReturn);
Shouldn't that be
result = sb.toString();
JSONObject jObject = new JSONObject(result);
You are trying to convert the String toReturn, which has invalid JSON data.
Here Amount is a JsonArray and you are trying to cast it in json object
JSONArray JsonArray2 = jsonobject.getJSONArray("amount");
Try this way
Related
This is the method I have written which sends a POST request to send an Email.
I am able to send the email and get the Response Code 200 Ok.
But I don't know how to get the JSON Response and convert it into an Object.
Can someone please tell me how to do this?
public void sendEmail() {
try {
URL url = new URL("https://mandrillapp.com/api/1.0/messages/send");
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true);
httpURLConnection.setRequestProperty("Content-Type", "application/json");
String data =
"{\"key\": \"" + mailchimpApiKey + "\", " +
"\"message\": {" +
"\"from_email\": \"from#gmail.com\", " +
"\"subject\": \"Hello World\", " +
"\"text\": \"Welcome to Mailchimp Transactional!\", " +
"\"to\": [{ \"email\": \"to#gmail.com\", \"type\": \"to\" }]}}";
byte[] out = data.getBytes(StandardCharsets.UTF_8);
OutputStream stream = httpURLConnection.getOutputStream();
stream.write(out);
System.out.println(httpURLConnection.getResponseCode() + " " + httpURLConnection.getResponseMessage());
httpURLConnection.disconnect();
} catch (IOException e) {
e.printStackTrace();
}
}
A basic search reveals: https://www.baeldung.com/httpurlconnection-post#8-read-the-response-from-input-stream
try(BufferedReader br = new BufferedReader(
new InputStreamReader(con.getInputStream(), "utf-8"))) {
StringBuilder response = new StringBuilder();
String responseLine = null;
while ((responseLine = br.readLine()) != null) {
response.append(responseLine.trim());
}
System.out.println(response.toString());
}
If the response is in JSON format, use any third-party JSON parsers such as Jackson library, Gson, or org.json to parse the response.
In addition to the answer by #mdre
I use the org.json library to convert responses into JSON Objects. The following method does exactly this:
import org.json.JSONException;
import org.json.JSONObject;
public static JSONObject convertResponseToJSONObject(String responseString) {
try {
JSONObject jsonObj = new JSONObject(responseString);
return jsonObj;
} catch (JSONException e) {
System.err.println(
"It is not possible to create a JSONObject from the input string, returning null. Exception:");
e.printStackTrace();
}
return null;
}
Note that the response only represents a JSON object if it starts with a {. If it starts with a [ the response represents a JSON array.
You can get errorStream or inputStream based on the response code you receive and get the response from it. Below example creates a BufferedReader from the stream
BufferedReader br = null;
if (100 <= httpURLConnection.getResponseCode() && httpURLConnection.getResponseCode() <= 399) {
br = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream()));
} else {
br = new BufferedReader(new InputStreamReader(httpURLConnection.getErrorStream()));
}
You can then read from the br and store data based on your requirement. Below will store data into StringBuilder
StringBuilder data = new StringBuilder();
String dataLine = null;
while ((dataLine = br.readLine()) != null) {
data.append(dataLine.trim());
}
System.out.println(data.toString());
Instead of printing as String you can also convert it into JSON by using JSON libraries. You may follow this guide
How do I parse an array of JSON objects from an external URL with the Java application? Here is an example of code, that I am using:
URL connectionUrl = new URL(/*some url*/);
connection = (HttpURLConnection) connectionUrl.openConnection();
String postData = "/*some post data*/";
connection.setDoOutput(true);
connection.setFixedLengthStreamingMode(postData.length());
OutputStream outputStream = null;
outputStream = connection.getOutputStream();
outputStream.write(postData.getBytes());
if(connection.getResponseCode() == 200) {
InputStream inputStream = connection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
String magicString = "", magicLine;
while((magicLine = bufferedReader.readLine()) != null) {
JSONArray jsonArr = new JSONArray(magicLine);
for(int i = 0; i < jsonArr.length(); i++) {
JSONObject currentEntity = jsonArr.getJSONObject(i);
}
}
return magicString;
And this one is the array of JSON objects, that gets echo'd out on some external URL:
[{"ID":"1","name":"test name","phone":"+37120000000","email":"test#cream.camp","date":"2020-12-17","time":"18:50:00","people_num":"4","active":"0"},{"ID":"2","name":"test name","phone":"+37120000000","email":"test#cream.camp","date":"2020-12-17","time":"18:50:00","people_num":"4","active":"1"}]
Unfortunately, the application fails with the following error:
org.json.JSONException: Value Authorization of type java.lang.String cannot be converted to JSONArray
You can create a POJO to hold JSON response. Use third-party jar such as Jackson. Something like the following:
ObjectMapper mapper = new ObjectMapper();
try {
YourPOJO obj = mapper.readValue(new URL("http://jsonplaceholder.typicode.com/posts/7"), YourPOJO.class);
System.out.println(usrPost);
} catch (Exception e) {
e.printStackTrace();
}
Refer to https://www.java2novice.com/java-json/jackson/jackson-client-read-from-api-url/
In my project , i separated back-end and front-end modules and run by providing REST api from back-end and call it by using Apache Http Client and GSON.
I want to provide multiple language like German,French... on UI(webpage).
On webpage , It shows like this "Schl��ssli Sch��negg, Wilhelmsh��he" , but in database and RestAPI json is "Schlössli Schönegg" .
How can I support multi language?
In back-end , i wrote Request methods like get,put,post and In Front-end, i used HttpClient and GSON to convert JSON to/from Java Object.
I tried inside the html but main problem is from GSON when it convert fromJSON() , the original JSON value ""Schlössli Schönegg" become "Schl��ssli Sch��negg, Wilhelmsh��he".
In RestAPI , JSON data is
{
"addressId": 3,
"buildingName": "Schlössli Schönegg",
"street": "Wilhelmshöhe",
"ward": "6003",
"district": "luzern",
"cityOrProvince": "luzern state",
"country": "Switzerland"
}
But in Front-end , Java Object String Data after GSON convert is
(..buildingName=Schlössli Schönegg, street=Wilhelmshöhe, ward=6003, district=luzern, cityOrProvince=luzern state, country=Switzerland)
Here , RestClient function code
public List<FakeEmployeeDTO> getAllEmployeeList() throws IOException {
HttpClient client = HttpClientBuilder.create().build();
HttpGet getRequest = new HttpGet(URL);
HttpResponse response = client.execute(getRequest);
Integer statusCode = response.getStatusLine().getStatusCode();
if (statusCode != 200) {
throw new SystemException(ERROR_MESSAGE + statusCode);
}
BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
String line = "";
StringBuilder jsonData = new StringBuilder();
while ((line = rd.readLine()) != null) {
jsonData.append(line);
}
response.getEntity().getContent().close();
rd.close();
logger.info(jsonData.toString());
Gson gson = new GsonBuilder().setDateFormat("dd-MMM-yyyy").create();
Type listType = new TypeToken<List<FakeEmployeeDTO>>() {
}.getType();
List<FakeEmployeeDTO> employeeList = gson.fromJson(jsonData.toString(), listType);
sortEmployeeListByFirstName(employeeList);
return employeeList;
}
Inside Employee, I have address atrribute , inside that address i have value like buildingNumber and Street, that value can be in any languages.
Try with this
(BufferedReader rd = new BufferedReader( new InputStreamReader(response.getEntity().getContent(),
"UTF-8"));)
Entire Code will end up with like this.
public List<FakeEmployeeDTO> getAllEmployeeList() throws IOException {
HttpClient client = HttpClientBuilder.create().build();
HttpGet getRequest = new HttpGet(url);
HttpResponse response = client.execute(getRequest);
Integer statusCode = response.getStatusLine().getStatusCode();
if (statusCode != 200) {
throw new SystemException(ERROR_MESSAGE + statusCode);
}
BufferedReader rd = new BufferedReader( new InputStreamReader(response.getEntity().getContent(),
"UTF-8")); // if it is not working please try with ("ISO-8859-1")
String line = "";
StringBuilder jsonData = new StringBuilder();
while ((line = rd.readLine()) != null) {
jsonData.append(line);
}
response.getEntity().getContent().close();
rd.close();
logger.info(jsonData.toString());
Gson gson = new GsonBuilder().setDateFormat("dd-MMM-yyyy").create();
Type listType = new TypeToken<List<FakeEmployeeDTO>>() {
}.getType();
List<FakeEmployeeDTO> employeeList = gson.fromJson(jsonData.toString(), listType);
sortEmployeeListByFirstName(employeeList);
return employeeList;}
Next time make sure to try with this, because you can use "try with resource"
try (BufferedReader reader = new BufferedReader(new InputStreamReader(
new URL("https://htt.your url.com" + URLEncoder.encode(query, "UTF-8") )
.openConnection().getInputStream()))) {
Microsoft Academic provided an API to get some general information from Microsoft academic. The response type is a Json Object. Using org.Json and following code, I have tried to read the response object but I have failed (need to download these jars + common-logging and common-codec) :
URIBuilder builder = new URIBuilder("https://api.projectoxford.ai/academic/v1.0/evaluate?");
builder.setParameter("expr", "Composite(AA.AuN=='jaime teevan')");
builder.setParameter("count", "100");
builder.setParameter("attributes", "Ti,CC");
URI uri = builder.build();
HttpGet request = new HttpGet(uri);
request.setHeader("Ocp-Apim-Subscription-Key", "Your-Key");
HttpClient httpclient = HttpClients.createDefault();
HttpResponse response = httpclient.execute(request);
HttpEntity entity = response.getEntity();
if (entity != null) {
JSONObject obj = new JSONObject(entity);
JSONArray arr = obj.getJSONArray("entities");
for (int i = 0; i < arr.length(); i++){
String post_id = arr.getJSONObject(i).getString("Ti");
System.out.println(post_id);
}
System.out.println(EntityUtils.toString(entity));
}
Which returns the following exception:
Exception in thread "main" org.json.JSONException: JSONObject["entities"] not found.
at org.json.JSONObject.get(JSONObject.java:471)
at org.json.JSONObject.getJSONArray(JSONObject.java:618)
How to fix this?
EDIT
Although it is easy to see an example of the response from the link I provided at the beginning of my question (Microsoft Academic), but for ease of readers I show it in here:
{
"expr": "Composite(AA.AuN=='jaime teevan')",
"entities":
[
{
"logprob": -15.08,
"Ti": "personalizing search via automated analysis of interests and activities",
"CC": 372,
},
{
"logprob": -15.389,
"Ti": "the perfect search engine is not enough a study of orienteering behavior in directed search",
"CC": 237,
}
]
}
Seems like the problem to me is you are not converting your response to string , you need to convert your response to string before passing it to JSONObject
HttpEntity entity = response.getEntity();
ByteArrayOutputStream os = new ByteArrayOutputStream();
try {
entity.writeTo(os);
} catch (IOException e1) {
}
String contentString = new String(os.toByteArray());
or other way is
InputStream instream = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(instream));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
String contentString = sb.toString(); // you can pass sb.toString() directly to jsonobject as well
and now pass contentString to JSONObject
JSONObject obj = new JSONObject(contentString);
JSONArray arr = obj.getJSONArray("entities");
Update : your can also use this which is also suggested by #Ömer Fadıl Usta
but i would strongly recommend to use HttpURLConnection for security and performance
Try to pass string JsonData to JSONObject :
if (entity != null) {
String jsonData = EntityUtils.toString(entity);
JSONObject obj = new JSONObject(jsonData);
........
.....
}
I am using a java backend. After a user performs an in-app purchase, the front-end sends me the receipt. In turn, I am to send the receipt to apple for confirmation; then apple is to decode the receipt and send me back a JSON dictionary. My question is about sending the receipt back to apple so that I may get the json response. I am using the code below. But I keep getting {"status":21002} from apple and something about "Invalid cookie header". Any ideas how to solve this?
String url = "https://buy.itunes.apple.com/verifyReceipt";
DefaultHttpClient client = null;
try {
String input = IOUtils.toString(is);
log.info("THE INPUTSTREAM: " + input);
JSONObject receipt = new JSONObject();
receipt.put("receipt-data", input);
client = new DefaultHttpClient();
HttpPost post = new HttpPost(url);
StringEntity entity = new StringEntity(receipt.toString());
entity.setContentType("application/json");
post.setEntity(entity);
HttpClientParams.setRedirecting(post.getParams(), false);
HttpResponse response = client.execute(post);
if (300 <= response.getStatusLine().getStatusCode()) {
throw new RuntimeException("No response from iTune store. status code: " + response.getStatusLine().getStatusCode());
}
if (null == response.getEntity()) {
log.info("Response is null");
throw new Exception("Response is null");
}
StringBuilder sb = new StringBuilder();
BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
for (String line; null != (line = reader.readLine());) {
sb.append(line);
}
JSONObject json = new JSONObject(sb.toString());
log.info("THE JSON" + json);
//Then work with json below
} catch (Exception e) {
throw new WebApplicationException(Response.status(Status.BAD_REQUEST).entity(e.getMessage()).build());
} finally {
if (null != client) {
client.getConnectionManager().shutdown();
}
}
No need cookie I think? try
HttpClientParams.setCookiePolicy(client.getParams(), CookiePolicy.IGNORE_COOKIES);