How I can save values to hash map from api? - java

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.

Related

Avoid calling toString with Objectmapper [Java 8]

I achieved what I was trying to accomplish, however, I am not satisfied with the unnecessary(?) string-parsing to arrive to my goal.
Here is the simplified code:
HttpURLConnection con = null;
URL url = new URL(URL);
con = (HttpURLConnection) url.openConnection();
// set connection parameters and make a GET-call
con.setRequestMethod("GET");
//Must be a better way?
InputStream inputStream = con.getInputStream();
BufferedReader in = new BufferedReader(new InputStreamReader(inputStream));
StringBuilder response = new StringBuilder();
String currentLine;
//Build the string from the response from con
while ((currentLine = in.readLine()) != null)
response.append(currentLine);
in.close();
ObjectMapper objectMapper = new ObjectMapper();
JsonNode jsonNode = objectMapper.readTree(response.toString());
// I only want the child-node
String myArray = jsonNode.get("parent").get("child").toString();
// Map the response to my object
List<Car> car = objectMapper.readValue(myArray, new TypeReference<List<Car>>(){});
There is so much manual parsing like
Reading the Http connection input stream to StringBuilder, then calling toString().
Retrieving the JsonNode and calling toString()
jsonNode.get("parent").get("child").toString()
to achieve my goal. I am by no means any senior- developer, and I gladly take advice and how I can remove "unnecessary" parsing.
The response from the API-call is in JSON already
Can only use HttpURLConnection-class for the API-call.
My Car class:
#JsonInclude(JsonInclude.Include.NON_NULL)
#JsonPropertyOrder({
"id",
"color"})
public class Car {
#JsonProperty("id")
public String id;
#JsonProperty("color")
public String color;
}
It is glad to see you want to improve your code.
Reading the input stream to StringBuilder and calling jsonNode.toString() is really unnecessary. In most of the case, there is always an useful API for your need.
Here is my suggestions:
Use ObjectMapper#readTree(InputStream) to simplify the part for consuming the HTTP input stream.
JsonNode jsonNode = objectMapper.readTree(con.getInputStream());
After retrieving the target JsonNode, create a JsonParser and then call
JsonParser jsonParser = new TreeTraversingParser(jsonNode.get("parent").get("child"));
objectMapper.readValue(jsonParser,new TypeReference<List<Car>>(){});

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.

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

Jackson json mapper

I am farily new to the Jackson json classes. I have just donwloaded version 2.2.1 which seems to be the best version for the jdk 1.5 which is what we have.
I have some json that I am trying to parse nicely but would like some help on how to use the jackson classes. Can someone please help me with an example of how I could map the data into a java object?
Here is my json...
[{"status":"GREEN","businessDate":"2014-07-25","transactionCount":510620},{"status":"GREEN","businessDate":"2014-07-24","transactionCount":532435},{"status":"GREEN","businessDate":"2014-07-23","transactionCount":379355},{"status":"GREEN","businessDate":"2014-07-22","transactionCount":321474},{"status":"GREEN","businessDate":"2014-07-21","transactionCount":322975}]
Here is what the call on my server classes looks like...
String requestURI = "http://mycompany:9080/ReportingManager/service/repManHealth/importHistoryTrafficLightStatus.json";
URL url = new URL(requestURI);
URLConnection conn = url.openConnection();
InputStream in = conn.getInputStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(in));
StringBuffer sb = new StringBuffer();
String line = null;
while ((line = rd.readLine()) != null) {
sb.append(line);
}
rd.close();
ObjectMapper mapper = new ObjectMapper();
// do some mapping here...
thanks
My question is can I use the jackson
Here is a small example:
ObjectMapper mapper = new ObjectMapper();
MyObject obj = mapper.readValue(sb.toString(), MyObject.class);
When MyObject is implemented in Bean Standard and the attribute names match the attribute names in JSON. All should work fine.
Otherwise use annotations to mapp your java object attributes correctly to the json attributes.
Thats all.
Jackson mapps the json objects to beans or pojos. You need to setup the beans having the fields like status, businessDate etc. For different names use annotations. And than you can use mapper to map the json string.
Using mapper your code looks like following
mapper.readValue(jsonString, YourBean.class);
Note here YourBean will be the POJO for holding json data.

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