Get JSON and use data in Java for Android Development Project - java

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

Related

How to retrieve URL nested inside JSONObject?

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").

Not able to parse the JSON data

I am working on an android project. I need help in this JSON data parsing which I am retrieving from the server:
{"item_name":["Navnita","Navnita","Navnita"],"username":["James","John","Jenny"],"review":["Its a relly nice restaurant for Vegetarians! :)","Cool!","Food is just great!"]}
I just want to populate the RecyclerView with the "username" and his "review".
Right now I am using the following code to parse the JSON data and populate an arrayList which in turn populates the RecyclerView but it gives me error(logcat below):
String result ....;
JSONObject jObject = new JSONObject(result);
JSONArray usernameJsonArray = jObject.getJSONArray("username");
JSONArray reviewJsonArray = jObject.getJSONArray("review");
for(int i=0;i<usernameJsonArray.length();i++){
String username = usernameJsonArray.getJSONObject(i).toString();
String review = reviewJsonArray.getJSONObject(i).toString();
getReviewFeedItemsArrayList.add(new GetReviewFeedItems(username,review));
}
I think that the problem is with this above code but I am not able to figure it out. Here's the logcat:
09-19 14:33:24.295 30572-30646/app.usrete.jayant.delvemitt W/System.err﹕ org.json.JSONException: Value James at 0 of type java.lang.String cannot be converted to JSONObject
09-19 14:33:24.305 30572-30646/app.usrete.jayant.delvemitt W/System.err﹕ at org.json.JSON.typeMismatch(JSON.java:100)
09-19 14:33:24.305 30572-30646/app.usrete.jayant.delvemitt W/System.err﹕ at org.json.JSONArray.getJSONObject(JSONArray.java:484)
directly write this in your for loop
String username=usernameJsonArray.getString(i);
Your inner data is not JsonObject its just string
you use the following to code to retrieve the data
JSONObject jObject = new JSONObject(result);
JSONArray usernameJsonArray = jObject.getJSONArray("username");
JSONArray reviewJsonArray = jObject.getJSONArray("review");
for(int i=0;i<usernameJsonArray.length();i++)
{
String username = usernameJsonArray.getString(i);
String review = reviewJsonArray.getString(i);
getReviewFeedItemsArrayList.add(new GetReviewFeedItems(username,review));
}
I think you are getting extra html junks with your echoed JSON format output from the http response.
Just add this after you convert your http response to string. This code will trim off the extra html junks and spit out the json format.
jsonData = jsonData.substring(jsonData.indexOf("{\""), jsonData.lastIndexOf("\"}") + 2);
Here "jsonData" is the String format from your http response.
After this follow the usual steps for JSON Parsing.
I'd use GSON. First convert your JSON into POJO classes, http://www.jsonschema2pojo.org/. Then parse your JSON data with GSON:
Gson gson = new Gson();
PojoClass obj = gson.fromJson(jsonString, PojoClas.class);

How to fetch a specific data from a url?

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

Using Json with java returns string with \" instead of "

Am using jsonobject and json array and converting the final result to string using jsonobject.toString() function and returning the string to browser.
Code snippet:
JSONArray VMs= new JSONArray();
JSONObject resultSet = new JSONObject();
for(Vector<String> stages : mrs)
{
VMs.put(new JSONObject().put("Vm",stages.get(0)));
}
resultSet.append("ServerDetails",(new JSONObject().put("Server",sName).append("Vms", stageNames)));
return resultSet.toString();
output on browser:
"{\"ServerDetails\":[{\"Server\":\"myserver45\",\"Vms\":[[{\"Vm\":\"vm1022\"},{\"Vm\":\"vm9875\"}]]}]}"
I don't want it to return this way. How do i make this return as follows without slashes-
"{"ServerDetails":[{"Server":"myserver45","Vms":[[{"Vm":"vm1022"},{"Vm":"vm9875"}]]}]}"
I don't understand why " gets replaced with \" everywhere. Please help.
If you are using net.sf.json json library, both jsonObject and jsonObject.toString() provide output values without string escape character. Which library you are using..?
Also try returning the original jsonObject itself than the one converted with toString. It might give you the desired result.
Alternate option would be to unescape the string which is send to browser. You can use stringescapeutils from org.apache.commons.lang for this return StringEscapeUtils.unescapeJava(resultSet.toString()) ;

JSONObject in JSONObject

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 ...

Categories