How to read resulting JSON data into Java ? - 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

Related

How I can save values to hash map from api?

try {
String apikey = "-------";
String url = "https://freecurrencyapi.net/api/v2/latest?apikey=" + apikey + "&base_currency=USD";
URL urlForGetRequest = new URL(url);
String readLine = null;
HttpURLConnection conection = (HttpURLConnection) urlForGetRequest.openConnection();
conection.setRequestMethod("GET");
int responseCode = conection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
BufferedReader in = new BufferedReader(new InputStreamReader(conection.getInputStream()));
StringBuffer response = new StringBuffer();
while ((readLine = in.readLine()) != null) {
response.append(readLine);
}
in.close();
System.out.println(response.toString());
} else {
throw new Exception("Error in API Call");
}
} catch (Exception ex) {
ex.printStackTrace();
}
How I can save values from api to Hashmap List? Where key will be first worth (e.g "JPY") and value will be worth of "JPY" (E.G 115).
I wanted to use Jackson lib, but I didn't find any information for how to do it.
enter image description here
What you're describing is caching. There are quite a few libraries to handle this, I would recommend EHCache, but I'm sure newer libraries have sprung up since last I did this kind of work. You should be using a framework to facilitate web calls. If you execute your calls from Spring, there are a set of annotations you can use that will do the caching for you behind the scenes.
Instead of having buffer reader consider using RestTemplate i,e
RestTemplate restTemplate = new RestTemplate();
String yurDestinationUrl= "http://blablalba";
ResponseEntity<String> response
= restTemplate.getForEntity(yurDestinationUrl + "/1", String.class);
ObjectMapper mapper = new ObjectMapper();
JsonNode root = mapper.readTree(response.getBody());
JsonNode name = root.path("name");
//then add extracted JsonNode to your desired map or list as you prefer
You can create a POJO (Plain Old Java Object) from the json response that you are dealing with.
There is an IntelliJ plugin which called RoboPOJOGenerator or by other websites which you can easily find with this search json to pojo
Or you can create that POJO manually.
After creating this class you should create gson from json string like below:
Gson gson = new Gson();
// JSON string to Java object
Currencies currencies = gson.fromJson(response.toString(), Currencies.class);
Finally you have a meaningful object instance which you can use/manipulate easily as you wish.

Gson HTTP response object

I am using Gson library for first time. I am making an HTTP request and pulling response (JSON response) and need to pull a specific result.
StringBuilder response;
try (BufferedReader in = new BufferedReader( new InputStreamReader(connection.getInputStream()))) {
String line;
response = new StringBuilder();
while((line = in.readLine()) != null) {
response.append(line);
}
}
Gson gson = new GsonBuilder()
.setPrettyPrinting()
.create();
System.out.println(gson.toJson(response));
The response looks like this below, and I need to pull only cardBackId:
[{\"cardBackId\":\"0\",\"name\":\"Classic\",\"description\":\"The only card back you\u0027ll ever need.\",\"source\":\"startup\",\"sourceDescription\":\"Default\",\"enabled\":true,\"img\":\"http://wow.zamimg.com/images/hearthstone/backs/original/Card_Back_Default.png\",\"imgAnimated\":\"http://wow.zamimg.com/images/hearthstone/backs/animated/Card_Back_Default.gif\",\"sortCategory\":\"1\",\"sortOrder\":\"1\",\"locale\":\"enUS\"
You could use JSONPath (which is a Java library for selecting parts of a JSON object) to extract just the part you need from the string.
Alternatively, you could write a class that only contains the field you want:
public class CardBackIdResponse {
public int cardBackId;
}
And then use Gson to unmarshall the JSON into your object:
CardBackIdResponse[] cardBackIdResponses = gson.fromJson(response.toString(), CardBackIdResponse[].class);
System.out.println("cardBackId = " + cardBackIdResponses[0].cardBackId);
When unmarshalling an object from JSON, if Gson cannot find a field in the object to populate with a value from the JSON, it will just discard the value. That's the principle we could use here.
Edit: Altered answer above to handle JSON array as per this SO question.

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("-----------");
}

How to read json data from HttpURLConnection

I am using HttpURLConnection from application1 to get json data from applicaton2. 'applicaton2' sets json data in Rest response object. How can i read that json data after getting response in application1.
Sample code:
Application1:
url = "url to application2";
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.connect();
Application2":
List<ModelA> lListModelAs = Entities data;
GenericEntity<List<ModelA>> lEntities = new GenericEntity<List<ModelA>>(lListModelAs) {};
lResponse = Response.ok(lEntities ).build();
I need to read above json data from urlConnection from response.
Any hints? Thanks in advance.
After setting up your HttpURLConnection.
BufferedReader reader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
StringBuilder response = new StringBuilder();
String line;
JsonObject obj = new JsonParser().parse(reader).getAsJsonObject();
boolean status = contentObj.get("status").getAsBoolean();
String Message = contentObj.get("msg").getAsString();
String Regno = contentObj.get("regno").getAsString();
String User_Id = contentObj.get("userid").getAsString();
String SessionCode = contentObj.get("sesscode").getAsString();
You can download the gson jar here enter link description here
Use dedicated library for json serialization/deserialization, Jackson for example. It will allow you to read json content directly from InputStream into POJOs that maps the response. It will be something like that:
MyRestResponse response=objectMapper.readValue(urlConnection.getInput(),MyRestResponse.class);
Looking good isnt it??
Here you have Jackson project GitHub page with usage examples.
https://github.com/FasterXML/jackson
You can use gson library
https://github.com/google/gson for parsing your data
Gson gson = new Gson();
YourClass objOfYourClass = gson.fromJson(urlConnection.getInputStream(), YourClass.class);

create json object from request body which contains JSON data

My request body contains JSON. i have to read that JSON save it as JSON object. And i don't have any pojo class representing the data in json. i tried this , and this and i am using com.ibm.json.java.JSONObject.i have tried this ,
BufferedReader ne = req.getReader();
StringBuffer jb = new StringBuffer();
try {
BufferedReader reader = req.getReader();
while ((line = reader.readLine()) != null)
jb.append(line);
} catch (Exception e) { /*report an error*/ }
JSONObject jsonObject = new JSONObject();
jsonObject.put("data", jb.toString());
above implementation is dumb because i am converting request header to string and adding it to jsonobject.
I think you should use public static JSONObject parse( java.lang.String str) in class JSONObject .Also there is no need to convert Reader to String as there are overloaded methods in JSONObject which take Inputstream and Reader eg public static JSONObject parse( java.io.Reader reader)

Categories