I am learning JavaEE, I have a JSONObject, and I need to retrieve a nested propriety "link", that is a URL to a PDF file (inside the JSON). Everything I try gives me error. Any hints or help would be appreciated.
The JSON: https://kalilcamera.com.br/teste.json (i want the URL http://www.africau.edu/images/default/sample.pdf inside this JSON)
My parse (working):
JSONObject testJson = new JSONObject( HttpUtil.send("POST", "https://kalilcamera.com.br/teste.json", "s", null).getResponseMessage());
My try to get the Link:
String urlPrescricaoMemedPDF = testJson.get("link").toString();
no matter what i try, gives me error.
my code from the debug perspective (Easy to undersand):
https://i.stack.imgur.com/584LR.png
Thanks for any help.
First you have to go through your json to get to the part where you can call get. Think of it as an nested Map, if you call get for something that is 3 layers down, you wont get anything usefull.
Second use getAsString instead of toString
final HttpRequest get = HttpRequest.newBuilder(URI.create("https://kalilcamera.com.br/teste.json"))
.GET()
.build();
final HttpClient httpClient = HttpClient.newHttpClient();
final HttpResponse<String> response = httpClient.send(get, HttpResponse.BodyHandlers.ofString());
final JsonObject bodyJson = JsonParser.parseString(response.body()).getAsJsonObject();
final JsonElement data = bodyJson.get("data");
final JsonElement zero = data.getAsJsonArray().get(0);
final JsonElement attributes = zero.getAsJsonObject().get("attributes");
final JsonElement link = attributes.getAsJsonObject().get("link");
System.out.println(link.getAsString());
prints : http://www.africau.edu/images/default/sample.pdf
Use object.getString("link") instead of get("link").
Related
I am fetching a JSONObject "result" from the following JSONObject:
{
"success" : true,
"message" : "",
"result" : {
"uuid" : "e606d53c-8d70-11e3-94b5-425861b86ab6"
}
}
I am using this code:
CloseableHttpClient httpclient = HttpClients.createDefault();
String url = "some url";
HttpGet httpget20 = new HttpGet(url);
httpget20.setHeader("apisign",buildHmacSignature(url, apisecret));
try ( CloseableHttpResponse response2 = httpclient.execute(httpget20)){
HttpEntity entity = response2.getEntity();
JSONObject obj2 = new JSONObject(EntityUtils.toString(entity));
JSONObject result = obj2.getJSONObject("result");
obj2 is the whole json object including "success", "message" and "result".
However, this line of code generates the following error message:
Exception in thread "AWT-EventQueue-0" org.json.JSONException: JSONObject["result"] is not a JSONObject.
I am not sure how a JSONObject can not be a JSONObject. Can someone explain the problem here?
JSONObject.getJSONObject can return a JSONObject only. It will not return boolean, long or String, and it will not return JSONObject.NULL in particular, because that is not a JSONObject itself (it says Java Object in the docs, and has a specific private type in the implementation).
Use isNull for checking it beforehand or just accept that it throws an exception and prepare for it. Of course you can also use the generic get and check the result against JSONObject.NULL afterwards, perhaps use instanceof, just none of these will make the code simpler and all of them will introduce casting/casting attempts at some point.
I was linking the Android docs for readability, but you can of course dig into source code too, like getJSONObject. You can find the NULL at the beginning of the same file if you are interested.
I am new on Android Developing. I am trying to get the JSON form URL and use it like this
TextView content = new TextView(this);
content.setText( --> CONTENT/HELLO WORLD <-- );
I have a JSON like this
{"content": "hello world"}
I already tried JSONParser, JSONObject it doesn't work for me. Please can you give me possible solution for this problem
If your response is a json, you can retrieve the value like this:
String sContent = response.getString("content");
content.setText(sContent);
But if your response is a string, do this:
JSONObject root = new JSONObject(response);
String sContent = root.getString("content");
content.setText(sContent);
This code should be inside a try...catch
HttpGet getRequest=new HttpGet("/rest/auth/1/session/");
getRequest.setHeaders(headers);
httpResponse = httpclient.execute(target,getRequest);
entity = httpResponse.getEntity();
System.out.println(EntityUtils.toString(entity));
Output as follows in json format
----------------------------------------
{"session":{"name":"JSESSIONID","value":"5F736EF0A08ACFD7020E482B89910589"},"loginInfo":{"loginCount":50,"previousLoginTime":"2014-11-29T14:54:10.424+0530"}}
----------------------------------------
What I want to know is how to you can manipulate this data using Java without writing it to a file?
I want to print name, value in my code
Jackson library is preferred but any would do.
thanks in advance
You may use this JSON library to parse your json string into JSONObject and read value from that object as show below :
JSONObject json = new JSONObject(EntityUtils.toString(entity));
JSONObject sessionObj = json.getJSONObject("session");
System.out.println(sessionObj.getString("name"));
You need to read upto that object from where you want to read value. Here you want the value of name parameter which is inside that session object, so you first get the value of session as JSONObject using getJSONObject(KeyString) and read name value from that object using function getString(KeyString) as show above.
May this will help you.
Here's two ways to do it without a library.
NEW (better) Answer:
findInLine might work even better. (scannerName.findInLine(pattern);)
Maybe something like:
s.findInLine("{"session":{"name":"(\\w+)","value":"(\\w+)"},"loginInfo":{"loginCount":(\\d+),"previousLoginTime":"(\\w+)"}}");
w matches word characters (letters, digits, and underscore), d matches digits, and the + makes it match more than once (so it doesnt stop after just one character).
Read about patterns here https://docs.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html
OLD Answer:
I'm pretty sure you could use a scanner with a custom delimiter here.
Scanner s = new Scanner(input).useDelimiter("\"");
Should return something like:
{
session
:{
name
:
JSESSIONID
,
value
:
5F736EF0A08ACFD7020E482B89910589
And so on. Then just sort through that list/use a smarter delimiter/remove the unnecessary bits.
Getting rid of every other item is a pretty decent start.
https://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html has info on this.
I higly recomend http-request built on apache http api.
private static final HttpRequest<Map<String, Map<String, String>>> HTTP_REQUEST = HttpRequestBuilder.createGet(yourUri, new TypeReference<Map<String, Map<String, String>>>{})
.addDefaultHeaders(headers)
.build();
public void send(){
ResponseHandler<Map<String, Map<String, String>>> responseHandler = HTTP_REQUEST.execute();
Map<String, Map<String, String>> data = responseHandler.get();
}
If you want use jackson you can:
entity = httpResponse.getEntity();
ObjectMapper mapper = new ObjectMapper();
Map<String, Map<String, String>> data = mapper.readValue(entity.getContent(), new TypeReference<Map<String, Map<String, String>>>{});
I am hitting a wall trying to get data loaded in a JSON array successfully passed to a java class that runs over the Neo4j server. My intent is to pass a list of entries from the client side to the server - nothing special here. What I am doing is reading the entries on the client side, loading those entries into JSON objects and then putting each JSON object into a JSON array which is then to be passed to the server for further processing.
Here is a section of the client side code that loads the json object and array. NOTE: the below is
just the json related code stripped down w/o the try/catch and other items resident in the code.
JSONArray jsonArray = new JSONArray();
JSONObject jsonObject = new JSONObject();
jsonObject.put("field1", field1Value1);
jsonObject.put("field2", field2Value1);
jsonObject.put("field3", field3Value1);
jsonArray.put(jsonObject);
JSONObject jsonObject = new JSONObject();
jsonObject.put("field1", field1Value2);
jsonObject.put("field2", field2Value2);
jsonObject.put("field3", field3Value2);
jsonArray.put(jsonObject);
Here is the client side code that handles the http post part of the equation - I believe this is ok.
StringEntity stringEntity = new StringEntity(jsonArray.toString());
stringEntity.setContentType("application/json");
HttpPost post = new HttpPost(
"http://"server":7474/db/data/ext/serverSideClass/graphdb/processJSONData");
post.setEntity(stringEntity);
HTTPPostResponseResults httpResponse = new HTTPPostResponseResults();
httpResponse.checkResponse(post);
Here is the method interface to the server side code and this is where I believe my problem lies. I am thinking the parameter type needs to something other than JSONArray but am not sure what.
#Name("processJSONData")
#Description("process the data passed in.")
#PluginTarget(GraphDatabaseService.class)
public String processJSONData(#Source GraphDatabaseService graphDb,
#Parameter(name = "jsonArray") JSONArray jsonArray) {
And... here is the error being thrown.
"message" : "java.util.ArrayList cannot be cast to java.util.Map",
"exception" : "BadInputException",
"fullname" : "org.neo4j.server.rest.repr.BadInputException",
"stacktrace" : [ "org.neo4j.server.rest.repr.formats.JsonFormat.readMap(JsonFormat.java:92)",
"org.neo4j.server.rest.repr.RepresentationFormat.readParameterList(RepresentationFormat.java:97)",
"org.neo4j.server.rest.web.ExtensionService.invokeGraphDatabaseExtension
The above should cover it for the items related to this posting. If there is anything needed to clarify this please let me know and I'll provide it. Thank you in advance.
I am trying to develop an android app which fetches data by visiting https://demo.vtiger.com/webservice.php?operation=getchallenge&username=admin.
The output of above url is {"success":true,"result":{"token":"53ba663902fd3","serverTime":1404724793,"expireTime":1404725093}}
But I want only the value of "token", so How can I fetch it from the result of above url?
Thanks for ur help.
Create JSONParser class in your application project.
Refer Below link for JSONParser class:
http://www.learn2crack.com/2013/10/android-json-parsing-url-example.html
then call it from your class
JSONParser jp=new JSONParser();
JsonObject object=jp.getJSONFromUrl(your url);
JsonObject object2=object.getJsonObject("result");
String Token=object2.getString("token");
Thats it...
Use JSONObject class to make an object from this json string.
Then get a token you want from the composed object.
String json = "{\"success\":true,\"result\":{\"token\":\"53ba663902fd3\",\"serverTime\":1404724793,\"expireTime\":1404725093}}";
JsonParser parser = new com.google.gson.JsonParser();
JsonElement elem = parser.parse(json);
String token = elem.getAsJsonObject().get("result").getAsJsonObject().get("token").getAsString();
System.out.print(token);