Gson HTTP response object - java

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.

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.

How can i read data from a json file saved in the sdcard?

I would like to know using Android Studio how to load & read a json file saved in the sdcard?
The json file contains simple json objects. Also after getting the data how can i parse it & set it as pojo.
Json example:
{
"name":"Abcd",
"id":"xyz"
}
Thanks.
Reading file:
InputStream iStream = new FileInputStream("filename.json");
BufferedReader bReader = new BufferedReader(new InputStreamReader(iStream));
String line;
String content = "";
while((line = bReader.readLine()) != null) {
content += line;
}
the easiest way to convert to POJO is to use one of the popular libraries (Gson, Jackson, etc). Using Gson:
Gson gson = new GsonBuilder().create();
gson.fromJson(content, Pojo.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)

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