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);
Related
I want to create an Application that can auto-create Memes. Every Meme from the API has different amounts of boxes (fields where the text can sit). Now I want to create an HTTP Request to get the fields for a specific meme ID.
The HTTP Request is working fine but I don't know how to deserialize and filter the received string.
Here is the JSON I want to Deserialize with GSON:
https://api.imgflip.com/get_memes
The solution is:
You need to get a JsonObject then in a JsonElement deserialize the "top-level-elements" and get it as a JsonArray. Then you can Loop through the array and get what you need.
JsonObject jsonObject = new Gson().fromJson(content.toString(), JsonObject.class);
JsonElement entry = jsonObject.getAsJsonObject("data").getAsJsonArray("memes");
JsonArray entryArray = entry.getAsJsonArray();
for (JsonElement element : entryArray) {
JsonObject jsonObjectLoop = element.getAsJsonObject();
if(jsonObjectLoop.get("id").getAsString().equals("14371066")) {
System.out.println(jsonObjectLoop.get("box_count").getAsString());
}
}
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").
I am currently using JsonObject and JsonParser of com.google.gson api (using gson-2.8.5 version) to parse and read the value form input JSON.
I have JSON filed like , smaple "resultCode":"SUCCESS", when I try to read the same value from json it gives the result as ""SUCCESS"" .
Every value I am reading, getting with double "" not sure why ? You can refer below screen of my debugging screen.
I am new to Json and parser, is that default behavior ?
I am expecting "SUCCESS", "S", "00000000" not like ""SUCCESS"" or ""S""
or ""00000000""
same I have highlighted in the below image .
Please share any idea how we can get apbsolute vlaue of string without """" double quote string it causing my string comparison fail.
String response_result = "{\"response\": {\"head\": {\"function\": \"acquiring.order.create\",\"version\": \"2.0\",\"clientId\": \"201810300000\",\"reqMsgId\": \"56805892035\",\"respTime\": \"2019-09-13T13:18:08+08:00\"},\"body\": {\"resultInfo\": {\"resultCode\": \"SUCCESS\",\"resultCodeId\": \"00000000\",\"resultStatus\": S,\"resultMsg\": \"SUCCESS\"},\"acquirementId\": \"2018080834569894848930\",\"merchantTransId\": \"5683668701112717398\",\"checkoutUrl\": \"http://localhost:8081/crm/operator/operator-search-init.action\"}},\"signature\":\"d+TUYLvt1a491R1e6aO8i9VwXWzVhfNgnhD0Du74f4RgBQ==\"}";
HttpInvoker.Result result = i.new Result(200, response_result);
JsonObject jo = new JsonParser().parse(response_result).getAsJsonObject();
String resultCode = jo.get("response").getAsJsonObject().get("body").getAsJsonObject().get("resultInfo").getAsJsonObject().get("resultCode").toString();
String resultCodeId = jo.get("response").getAsJsonObject().get("body").getAsJsonObject().get("resultInfo").getAsJsonObject().get("resultCodeId").toString();
String resultStatus = jo.get("response").getAsJsonObject().get("body").getAsJsonObject().get("resultInfo").getAsJsonObject().get("resultStatus").toString();
String checkoutUrl = jo.get("response").getAsJsonObject().get("body").getAsJsonObject().get("checkoutUrl").toString();
if ( RESULT_CODE_GCASH_SUCCESS.equals(resultCode)
&& RESULT_STATUS_SUCCESS.equals(resultStatus)
&& StringUtils.isNotEmpty(checkoutUrl)) {
log.error("Testing ".concat(resultCode).concat(resultStatus).concat(checkoutUrl));
}
log.error("Testing ".concat(resultCode).concat(resultStatus).concat(checkoutUrl));
}
This is my input JSON
{
"response":{
"head":{
"function":"acquiring.order.create",
"version":"2.0",
"clientId":"201810300000",
"reqMsgId":"56805892035",
"respTime":"2019-09-13T13:18:08+08:00"
},
"body":{
"resultInfo":{
"resultCode":"SUCCESS",
"resultCodeId":"00000000",
"resultStatus":"S",
"resultMsg":"SUCCESS"
},
"acquirementId":"2018080834569894848930",
"merchantTransId":"5683668701112717398",
"checkoutUrl":"http://localhost:8081/crm/operator/operator-search-init.action"
}
},
"signature":"d+TUYLvtI38YL2hresd98Ixu1BXccvvh1IQMiHuMXUEeW/N5exUsW491R1e6aO8i9VwXWzVhfNgnhD0Du74f4RgBQ=="
}
JsonParser parses your json into JsonElement structure. The behaviour that you see is a normal since you are using toString method of JsonElement. To achieve your goal just use JsonElement::getAsString method :
String resultCode = jo.get("response").getAsJsonObject().get("body").getAsJsonObject().get("resultInfo").getAsJsonObject().get("resultCode").getAsString();
which gives SUCCESS instead of "SUCCESS"
Note that JsonElement is an abstract class and classes, that extend this class, will override those helper getAs... methods. In your case JsonPrimitive::getAsString will be invoked.
Also you could create a POJO class for your json and use Gson::fromJson to parse json into object of your POJO class.
With the input from #Michalk:
I understand that easy way to read JSON data is using Gson::fromJson and creating POJO class for out json.
I have generated POJO Classes supplying my sample input JSON using this link
and Now I have POJO Classes called : CreateOrderJSONResponse
Gson::fromJson
Sample :
Gson gson = new Gson();
CreateOrderJSONResponse responseJson = gson.fromJson(inputJSON, CreateOrderJSONResponse.class);
Accessubg data :
String resultCodeText = responseJson.getResponse().getBody().getResultInfo().getResultCode();
String resultCodeId = responseJson.getResponse().getBody().getResultInfo().getResultCodeId();
String resultStatus = responseJson.getResponse().getBody().getResultInfo().getResultStatus();
String checkoutUrl = responseJson.getResponse().getBody().getCheckoutUrl();
Above Gson::fromJson example works smooth and it looks neat compare to direct accessing the filed with below sample code :
JsonObject jo = parser.parse(inputJSON).getAsJsonObject();
String resultCodeText = jo.get("response").getAsJsonObject().get("body").getAsJsonObject().get("resultInfo").getAsJsonObject().getAsJsonPrimitive("resultCode").getAsString();
String resultCodeId = jo.get("response").getAsJsonObject().get("body").getAsJsonObject().get("resultInfo").getAsJsonObject().getAsJsonPrimitive("resultCodeId").getAsString();
String resultStatus = jo.get("response").getAsJsonObject().get("body").getAsJsonObject().get("resultInfo").getAsJsonObject().getAsJsonPrimitive("resultStatus").getAsString();
String checkoutUrl = jo.get("response").getAsJsonObject().get("body").getAsJsonObject().getAsJsonPrimitive("checkoutUrl").getAsString();
Note :
I have found this link of JSON or JAVA, SCALA, POJO generator tools as GitHub access you can access here
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
I have an API Output like this:
{"user" : {"status" : {"stat1" : "54", "stats2" : "87"}}}
I create a simple JSONObject from this API with:
JSONObject json = getJSONfromURL(URL);
After this I can read the data for User like this:
String user = json.getString("user");
But how do I get the Data for stat1 and stat2?
JSONObject provides accessors for a number of different data types, including nested JSONObjects and JSONArrays, using JSONObject.getJSONObject(String), JSONObject.getJSONArray(String).
Given your JSON, you'd need to do something like this:
JSONObject json = getJSONfromURL(URL);
JSONObject user = json.getJSONObject("user");
JSONObject status = user.getJSONObject("status");
int stat1 = status.getInt("stat1");
Note the lack of error handling here: for instance the code assumes the existence of the nested members - you should check for null - and there's no Exception handling.
JSONObject mJsonObject = new JSONObject(response);
JSONObject userJObject = mJsonObject.getJSONObject("user");
JSONObject statusJObject = userJObject.getJSONObject("status");
String stat1 = statusJObject.getInt("stat1");
String stats2 = statusJObject.getInt("stats2");
from your response user and status is Object so for that use getJSONObject and stat1 and stats2 is status object key so for that use getInt() method for getting integer value and use getString() method for getting String value.
To access properties in an JSON you can parse the object using JSON.parse and then acceess the required property like:
var star1 = user.stat1;
Using Google Gson Library...
Google Gson is a simple Java-based library to serialize Java objects to JSON and vice versa. It is an open-source library developed by Google.
// Here I'm getting a status object inside a user object. Because We need two fields in user object itself.
JsonObject statusObject= tireJsonObject.getAsJsonObject("user").getAsJsonObject("status");
// Just checking whether status Object has stat1 or not And Also Handling NullPointerException.
String stat1= statusObject.has("stat1") && !statusObject.get("stat1").isJsonNull() ? statusObject.get("stat1").getAsString(): "";
//
String stat2= statusObject.has("stat2") && !statusObject.get("stat2").isJsonNull() ? statusObject.get("stat2").getAsString(): "";
If You have any doubts , Please let me know in comments ...