Can not find the Json object (Using org.json) - java

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

Related

Parse JSON array of objects from url Java

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/

java.lang.IllegalArgumentException: Illegal character in query at index 59

What i am doing:
I am trying to make a reverse geocoding in android
I am getting error as::
java.lang.IllegalArgumentException: Illegal character in query at index 59: http://maps.google.com/maps/api/geocode/json?address=Agram, Bengaluru, Karnataka, India&sensor=false
NOte: that request gets a json response in browser but not from my class below
This line is giving this error::
HttpGet httpget = new HttpGet(url);
JSONfunctions.java
public class JSONfunctions {
public static JSONObject getJSONfromURL(String url) {
InputStream is = null;
String result = "";
JSONObject jArray = null;
// Download JSON data from URL
try {
HttpClient httpclient = new DefaultHttpClient();
HttpGet httpget = new HttpGet(url);
HttpResponse response = httpclient.execute(httpget);
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 {
jArray = new JSONObject(result);
} catch (JSONException e) {
Log.e("log_tag", "Error parsing data " + e.toString());
}
return jArray;
}
}
Use URLEncoder.encode() to encode the value of your address parameter "Agram, Bengaluru, Karnataka, India" before putting it in the URL string so that it becomes something like
http://maps.google.com/maps/api/geocode/json?address=Agram,+Bengaluru,+Karnataka,+India&sensor=false
i.e. spaces changed to + and other special octets represented as %xx.
Browsers do smart URL encoding for strings entered in the address bar automatically so that's why it works there.
Build your url like,
final StringBuilder request = new StringBuilder(
"http://maps.googleapis.com/maps/api/geocode/json?sensor=false");
request.append("&language=").append(Locale.getDefault().getLanguage());
request.append("&address=").append(
URLEncoder.encode(locationName, "UTF-8"));
I am using httpclient 4.3.3
String messagestr = "Welcome to Moqui World";
String url="http://my.example.com/api/sendhttp.phpauthkey="+URLEncoder.encode("17djssnvndkfjb110d3","UTF-8")+"&mobiles=91"+URLEncoder.encode(contactNumber,"UTF-8")+"&message="+URLEncoder.encode(messagestr,"UTF8")+"&sender="+URLEncoder.encode("WMOQUI","UTF-8")+"&route=4";
HttpClient client = HttpClientBuilder.create().build();
HttpGet request = new HttpGet(url);
HttpResponse response = client.execute(request);
It's working fine for me. I hope this may help you.

Jsonexception - cannot be converted to JSONObject [duplicate]

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

JSONArray and encoded image on Android tablet

I have a problem with my first Android App. I want to ask a PHP server for a name and image, using an cardid. This works well, but JSONArray throws an exception when I try to split up the long string I get. This is the method I use on the Android device:
public static Object[] getIdCardOwner(String card)
{
JSONArray jArray;
String result = null;
InputStream is = null;
StringBuilder sb=null;
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("cardid",card));
Object returnValue[] = new Object[2];
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(SERVER_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 to string
try{
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"utf-8"), 16);
sb = new StringBuilder();
sb.append(reader.readLine() + "\n");
String line="0";
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());
}
//paring data
try{
jArray = new JSONArray(result);
JSONObject json_data=null;
for(int i=0;i<jArray.length();i++){
json_data = jArray.getJSONObject(i);
returnValue[0] = json_data.getString("name");
returnValue[1] = json_data.getString("image");
}
}
catch(JSONException e1){
Log.e("log_tag", "Error converting result "+e1.toString());
} catch (ParseException e1) {
e1.printStackTrace();
}
return returnValue;
}
This is the String result I get before the exception happens:
{"0":"4016612622","card":"4016612622","1":"Peter Poulsen","name":"Peter Poulsen","2":"\/9j\/4QAYRXhpZgAASUkqAAgAAAAAAAAAAAAAAP\/sABFEdWNreQABAAQAAAAeAAD\/4QMpaHR0cDovL25zLmFkb2JlLmNvbS94YXAvMS4wLwA8P3hwYWNrZXQgYmVnaW49Iu+7vyIgaWQ9Ilc1TTBNcENlaGlIenJlU3pOVGN6a2M5ZCI\/PiA8eDp4bXBtZXRhIHhtbG5zOng9ImFkb2JlOm5zOm1ldGEvIiB4OnhtcHRrPSJBZG9iZSBYTVAgQ29yZSA1LjAtYzA2MCA2MS4xMzQ3NzcsIDIwMTAvMDIvMTItMTc6MzI6MDAgICAgICAgICI+IDxyZGY6UkRGIHhtbG5zOnJkZj0iaHR0cDovL3d3dy53My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o60jcyhE+IXJ2b5mQwCoxPiFa0c1nNnAx0KLoQI4ZGM8aHKeAS0joq8t2pZgrXHMZw2lNmtHiBdvIppPn0UYc3juHq3btHGrpvL4lV9bSi\/ZdonITqxFqRtiCEeC17eIZwc3j1uK6c6kNkLn8nQSN0ZDrp0Wh7pG6W2smQYqnYDcW2xZtrAYZIr+uEiMOdXadtJEz27KcYyMt2gIyPVN4vEpoidkREy1ICldIRgT1Kh7wLK2U7BkqlZieFbnJoklUTLdMlVVGfY8DBL0UoywlBTicKjEZu+qFF0IAmo1XGmzadDp9EOoWx3RxqMhVA04NOMvciWS27jI0SOByBgS10KvTEd2OqmDerlCYCcjonASPizBMrgAexTPGI3dkmV+sVOWyDKpffuLdl3k3OS5wMhULLskpKpFrByLX6qvHAD66oc2S9FOUC4bQaqtGdpZ0FSicJbEKUThMiGtjHQoOhIQ1+6hKYbGUbUbU5N11c5IRJrPuDT+7+qv1coSiM5VOsBzE9UqyudR3Vlh2TE5q8Gr\/2TE6u6VdzW1KzPft6lLJlI+RdECd2yxZyDMnslSJkWXACdFYppc6IJSbO01EJhiz\/RWBXtiyRYWwOqhs0qtIUYuubU0DCGUyauqe0KYoTNvVCfszP41BBbCEJmpCWuNU3WPmGQhNGdytMVPgqIFb6oQqMx0BU+T+6uUivoUISY0StMm8Q\/qqmTLywhClmtSeFxCFJYIQhIR\/\/Z"}
And this is the error I get:
05-14 14:13:00.723: E/log_tag(359): Error converting result org.json.JSONException: Value {"image":"\/9j\/4QAYRXhpZgAASUkqAAgAAAAAAAAAAAAAAP\/sABFEdWNreQABAAQAAAAeAAD\/4QMpaHR0cDovL25zLmFkb2JlLmNvbS94YXAvMS4wLwA8P3hwYWNrZXQgYmVnaW49Iu+7vyIgaWQ9Ilc1TTBNcENlaGlIenJlU3pOVGN6a2M5ZCI\/PiA8eDp4bXBtZXRhIHhtbG5zOng9ImFkb2JlOm5zOm1ldGEvIiB4OnhtcHRrPSJBZG9iZSBYTVAgQ29yZSA1LjAtYz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QoOhIQ1+6hKYbGUbUbU5N11c5IRJrPuDT+7+qv1coSiM5VOsBzE9UqyudR3Vlh2TE5q8Gr\/2TE6u6VdzW1KzPft6lLJlI+RdECd2yxZyDMnslSJkWXACdFYppc6IJSbO01EJhiz\/RWBXtiyRYWwOqhs0qtIUYuubU0DCGUyauqe0KYoTNvVCfszP41BBbCEJmpCWuNU3WPmGQhNGdytMVPgqIFb6oQqMx0BU+T+6uUivoUISY0StMm8Q\/qqmTLywhClmtSeFxCFJYIQhIR\/\/Z","2":"\/9j\/4QAYRXhpZgAASUkqAAgAAAAAAAAAAAAAAP\/sABFEdWNreQABAAQAAAAeAAD\/4QMpaHR0cDovL25zLmFkb2JlLmNvbS94YXAvMS4wLwA8P3hwYWNrZXQgYmVnaW49Iu+7vyIgaWQ9Ilc1TTBNcENlaGlIenJlU3pOVGN6a2M5ZCI\/PiA8eDp4bXBtZXRhIHhtbG5zOng9ImFkb2JlOm5zOm
Can anyone tell me, what I'm doing wrong and how to fix it?
Thanks in advance
Peter
The data they're supplying for json_data.getString("image") is not a string.
It's an image.
Check the JSON manually. It it's outputting image data then you need to get them to change the JSON. E.g. it should look like this:
"src": "Images/theImage.png",

How to call PHP function from Android?

I want to call specific php function on server and also to send some parameters.
Till now I achieved that I can open php file using HttpClient and executed data transfer to Json and show that in my app.
So, now I want to be able to call specific function and send parameter to it, how can I do that??
Sorry I didn't mansion that I need to call that function from Android.
here some code:
try {
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("http://10.0.2.2/posloviPodaci/index.php");
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);
sb = new StringBuilder();
sb.append(reader.readLine() + "\n");
String line = "0";
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());
}
// Parsing data
JSONArray jArray;
try {
jArray = new JSONArray(result);
JSONObject json_data = null;
items = new String[jArray.length()];
for(int i = 0; i < jArray.length(); i++) {
json_data = jArray.getJSONObject(i);
items[i] = json_data.getString("naziv");
}
} catch (Exception e) {
// TODO: handle exception
}
Thanks in advance,
Wolf.
If you are working with an MVC framework, such as CakePHP, you can simply create a route to a function that will output whatever JSON you'd like.
Otherwise,
You can utilize something simple at the top of your index.php such as this:
<?php
function foo($bar) { echo $bar; }
if(isset($_GET['action']) && (strlen($_GET['action']) > 0)) {
switch($_GET['action']) :
case 'whatever':
echo json_encode(array('some data'));
break;
case 'rah':
foo(htmlentities($_GET['bar']));
break;
endswitch;
exit; # stop execution.
}
?>
This will let you call the url with a parameter of action.
http://10.0.2.2/posloviPodaci/index.php?action=whatever
http://10.0.2.2/posloviPodaci/index.php?action=rah&bar=test
If you need to pass more sensitive data, I recommend you stick with $_POST and utilize some form of encryption.
You can handle that on php side. Create a Json object with a field called command and maybe a list of arguments.
On the php end after you decode the json just do:
if($obj.command == "foo"){
foo($obj.arg[0],$obj.arg[1]);
}

Categories

Resources