How to get JSON data using GSON - java

This has probably been asked before, but I do not know the terminology for my question, therefore do not know what to look up.
I am using GSON and Java trying to get information from a parsed JSONElement.
Java code:
JsonParser parser = new JsonParser();
String url = "https://chapel-logs.herokuapp.com/attendance";
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
// optional default is GET
con.setRequestMethod("GET");
//add request header
con.setRequestProperty("Accept", "application/json");
int responseCode = con.getResponseCode();
System.out.println("\nSending 'GET' request to URL : " + url);
System.out.println("Response Code : " + responseCode);
BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
//print result
JsonElement element = parser.parse(response.toString());
if (element.isJsonObject()) {
JsonObject albums = element.getAsJsonObject();
System.out.println(albums.get("students")); //prints out data in students
System.out.println(albums.get("students.LastChapelAttended")); //error
}
My JSON :
{"students":[{"LastChapelAttended":{"Loc":"","Chapel":"WhyChapel","Year":2018,"Month":9,"Day":6,"Hour":15,"Min":14,"Sec":28},"StudNum":"F02660934","Attendance":17},{"LastChapelAttended":{"Loc":"","Chapel":"WhyChapel","Year":2018,"Month":9,"Day":5,"Hour":19,"Min":49,"Sec":11},"StudNum":"002660934","Attendance":2},{"LastChapelAttended":{"Loc":"","Chapel":"WhyChapel","Year":2018,"Month":9,"Day":4,"Hour":20,"Min":35,"Sec":57},"StudNum":"002643472","Attendance":2},{"LastChapelAttended":{"Loc":"","Chapel":"WhyChapel","Year":2018,"Month":9,"Day":7,"Hour":5,"Min":34,"Sec":54},"StudNum":"002664906","Attendance":1}]}
The data I am trying to get is: LastChapelAttended, however LastChapelAttended is within students. In JavaScript the equivalent to what I am trying would be students.LastChapelAttended if that helps.
Thanks in advance!

JsonObject jObj=(JsonObject)albums.get("students").getAsJsonArray().get(0);
System.out.println(jObj.get("LastChapelAttended"));
Get it as a JsonArray and then loop through the array to get LastChapelAttended.

First, students is not an object but an array. Thus students.LastChapelAttended should not work in any language. If you want to retrieve LastChapelAttended of the first student in the array students[0].LastChapelAttended should work.
I am not familiar with gson, but I think what you want to do is something like this:
if (element.isJsonObject()) {
JsonObject albums = element.getAsJsonObject();
JsonArray students = albums.getAsJsonArray("students");
for (JsonElement student : students) {
System.out.println(albums.getAsJsonObject().get("LastChapelAttended"));
}
}

You can check this out for help Difference between JSONObject and JSONArray
Students is a JsonArray
LastChapelAttended is a JSONObject you can get it by calling
json = (json data)
JsonParser parser = new JsonParser();
JsonObject rootObj = parser.parse(json).getAsJsonObject();
JsonArray studentsArray = rootObj.getAsJsonArray("students");
for (JsonElement stu : studentsArray) {
JsonObject student = stu.getAsJsonObject();
JsonObject LastChapelAttended = student.getAsJsonObject("LastChapelAttended");
}

Just iterate over the student array
albums.getAsJsonArray("students")
.forEach(student -> System.out.println(student.getAsJsonObject()
.get("LastChapelAttended")));

Related

Loop all data from json in java

I have a problem with Java when I try to display all of content from cmd's elements. So here is my code:
public static void main(String[] args) throws Exception {
// Json Stream Reader
String jsonS = "";
// Connect to web api
URL url = new URL("http://b50172e8.ngrok.io/api/plugin/521100d075c1284b944841394e157744");
// Make Connection
URLConnection conn = url.openConnection();
conn.setRequestProperty("Accept","*/*");
conn.connect();
// Stream reader
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String inputLine;
while((inputLine = in.readLine()) != null) {
jsonS+=inputLine;
}
// Read json response
Gson gson = new Gson();
// Json Object
JsonObject jsonObject= gson.fromJson(jsonS, JsonObject.class);
JsonElement data = jsonObject.get("data");
System.out.println(data);
// Close connection
in.close();
}
Output:
[{"cmd":"cmd-1"},{"cmd":"cmd-2"},{"cmd":"cmd-3"}]
I want to use foreach of cmd to display the following:
cmd-1
cmd-2
cmd-3
Try this code. I hope it helps.
public static void main(String[] args) throws Exception {
// Json Stream Reader
String jsonS = "";
// Connect to web api
URL url = new URL("http://b50172e8.ngrok.io/api/plugin/521100d075c1284b944841394e157744");
// Make Connection
URLConnection conn = url.openConnection();
conn.setRequestProperty("Accept","*/*");
conn.connect();
// Stream reader
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String inputLine;
while((inputLine = in.readLine()) != null) {
jsonS+=inputLine;
}
// Read json response
Gson gson = new Gson();
// Json Object
JsonObject jsonObject= gson.fromJson(jsonS, JsonObject.class);
JsonArray data = jsonObject.getAsJsonArray("data");
//here data is JsonArray and it contains everithing: [{"cmd":"cmd-1"},{"cmd":"cmd-1"},{"cmd":"cmd-1"}]
data.forEach(el -> {
//Get Json object which has key and value -> {"cmd":"cmd-1"}
JsonObject jo = el.getAsJsonObject();
//get the value as Json element -> "cmd-1"
JsonElement je = jo.get("cmd");
//Then make the json element string
String value = je.getAsString();
System.out.println(value);
});
//System.out.println(data);
// Close connection
in.close();
}

Receive data from a webservice using REST API

I need to get specific data from this API http://countryapi.gear.host/v1/Country/getCountries?pName=Australia, convert it to String and write out on the console. I want to get data only for Australia. How can I get data in String format only for Name and Alpha2Code like this:
Australia, AU? I was trying to use EntityUtils.toString(response) but it doesn't work.
This is my code:
public class Client {
public static void main(String[] args) throws ClientProtocolException, IOException {
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet("http://countryapi.gear.host/v1/Country/getCountries?pName=Australia");
request.addHeader("accept", "application/json");
HttpResponse response = client.execute(request);
HttpEntity entity = response.getEntity();
InputStream stream = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(stream));
String line = reader.readLine();
System.out.println(line);
}
}
The code actually return JSON for Australia, like this:
enter image description here
Try something like this:
Gson gson = new Gson();
JsonObject result = gson.fromJson(line, JsonObject.class);
JsonArray response = result.getAsJsonArray("Response");
Country country = gson.fromJson(response, Country.class);
You can use java api for json parsing. I am just writing a sample code. YOu can explore json parsing api more on below URL:
http://www.oracle.com/technetwork/articles/java/json-1973242.html
JsonObject obj = rdr.readObject();
JsonArray results = obj.getJsonArray("data");
for (JsonObject result : results.getValuesAs(JsonObject.class)) {
System.out.print(result.getJsonObject("name").getString("name"));
System.out.print(": ");
System.out.println(result.getString("message", ""));
System.out.println("-----------");
}

Parsing JSON Object from a JSON array

I am currently developing an app and need to parse JSON objects from inside an unnamed array.
I can only manage to parse JSON arrays with a name such as this one: http://jsonparsing.parseapp.com/jsonData/moviesDemoItem.txt.
The code that I used for the one above is
protected String doInBackground(String... params) {
HttpURLConnection connection = null;
BufferedReader reader = null;
try {
URL url = new URL(params[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
String asd = buffer.toString();
JSONObject parentObject = new JSONObject(asd);
JSONArray parentArray = parentObject.getJSONArray("movies");
JSONObject fObject = parentArray.getJSONObject(0);
String movie = fObject.getString("movie");
int year = fObject.getInt("year");
return movie + year;
The code includes "movies" which is the array name .
What should I change to parse only the objects from within a JSON array such as https://restcountries.eu/rest/v1/all?
Your countries list is simply an array. Doesn't need a name.
Simply replace
JSONObject parentObject = new JSONObject(asd);
with
JSONArray parentObject = new JSONArray(asd);
See this post for how to iterate over that array to parse the remainder of the objects.
How to parse JSON in Android
Starting something like
for (int i=0; i < parentObject.length(); i++) {
Alternatively, Volley's JsonArrayRequest would be useful, or learning about Retrofit+Gson would be even better if you don't feel like manually parsing the JSON data yourself.

How to get values from mixed type json?

I have string in JSON format. For example:
{
"blockedStatus":true,
"cars":[
"RAW:123",
"TVU:123"
],
"phones":[
"370665566",
"3706324231"
]
}
This is output from server. I need to get seperate values but I don't know how to do it.
Tried this:
BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
StringBuilder builder = new StringBuilder();
for (String line = null; (line = reader.readLine()) != null;) {
builder.append(line).append("\n");
}
JSONTokener tokener = new JSONTokener(builder.toString());
JSONArray finalResult = new JSONArray(tokener);
Log.e("IO-OUTPUT", builder.toString()); //prints json output
Log.e("finalResult (1)", finalResult.getString(1));
But I get ant exception:
W/System.err(31249): org.json.JSONException: Value {"blockedStatus":true,"cars":["RAW"],"phones":["65431"]} of type org.json.JSONObject cannot be converted to JSONArray
Is there another way to get values? Because calculating symbols and getting values from it will be too hard
change
JSONTokener tokener = new JSONTokener(builder.toString());
JSONArray finalResult = new JSONArray(tokener);
to
JSONObject jsonObject = new JSONObject(builder.toString());
JSONArray carsResult = jsonObject.getJSONArray("cars");
JSONArray phoneResult = jsonObject.getJSONArray("phones");
your string rapresent a JSONObject which contains two JSONArray's, cars and phones, and a pair key/value blockedStatus .
Also, if you read the logcat, it says:
type org.json.JSONObject cannot be converted to JSONArray
You can not convert a JSONObject to a JSONArray, which means the you have a JSONObject
Try this
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet();
request.setURI(new URI(url));
HttpResponse response = client.execute(request);
InputStream ips = response.getEntity().getContent();
responseString = response.toString();
responseString = intputStreamToStringConvertor(ips);
JSONObject object = new JSONObject(responseString);
Boolean status = object.getBoolean("blockedStatus");
JsonArray cars = object.getJSONArray("cars");
JsonArray phones = object.getJSONArray("phones");

How to read resulting JSON data into Java ?

I am trying to read results of a JSON request into java, yet
The partial output of my JSON request looks like this :
"route_summary": {
"total_distance": 740,
"total_time": 86,
"start_point": "Marienstraße",
"end_point": "Feldbergstraße"
}
I would like to use the standard json library to extract the values in total_distance.
However I only seem to be able to get the 'route_summary' by doing this :
JSONObject json = null;
json = readJsonFromUrl(request);
json.get("route_summary");
Where
public static JSONObject readJsonFromUrl(String url) throws IOException, JSONException {
InputStream is = new URL(url).openStream();
try {
BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));
String jsonText = readAll(rd);
JSONObject json = new JSONObject(jsonText);
return json;
} finally {
is.close();
}
}
What I want is get 'into' route_summary, any clue / tip would be great !
You need to get route_summary, as you already did, and from that object you need to get the total_distance. This will give you back the route_summary.total_distance.
Code sample:
JSONObject object = new JSONObject(s);
int totalDistance = object.getJSONObject("route_summary").getInt("total_distance");
I would recommend you to use GSON library. You can create class which will represent the message and then automatically map JSON to object by invoking function: gson.fromJson(message, YourMessageClass.class).getRoute_summary().
Here is the example of such approach: https://sites.google.com/site/gson/gson-user-guide/#TOC-Object-Examples

Categories