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);
Related
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.
I am writing a Java class to access a third-party public REST API web service, that is secured using a specific APIKey parameter.
I can access the required Json array, using the JsonNode API when I save the json output locally to a file.
E.g.
JsonNode root = mapper.readTree(new File("/home/op/Test/jsondata/loans.json"));
But, if I try to use the live secured web URL with JsonNode
E.g.
JsonNode root = mapper.readTree(url);
I am getting a:
com.fasterxml.jackson.core.JsonParseException: Unexpected character ('<' (code 60))
which suggests that I have a type mismatch. But I am assuming that it is more likely to be a connection issue.
I am handling the connection to the REST service:
private static String surl = "https://api.rest.service.com/xxxx/v1/users/xxxxx/loans?apikey=xxxx"
public static void main(String[] args) {
try {
URL url = new URL(surl);
JsonNode root = mapper.readTree(url);
....
}
I have also tried to use:
URL url = new URL(surl);
HttpURLConnection httpcon = (HttpURLConnection) url.openConnection();
InputStream isr = httpcon.getInputStream();
JsonNode root = mapper.readTree(isr);
with the same result.
When I remove the APIKey I receive a Status 400 Error. So I think I must not be handling the APIKey parameter.
Is there way to handle the call to the secured REST service URL using JsonNode? I would like to continue to use the JsonNode API, as I am extracting just two key:value pairs traversing multiple objects in a large array.
Just try to simply read response into string and log it to see what's actually going on and why you do not receive JSON from server.
URL url = new URL(surl);
HttpURLConnection httpcon = (HttpURLConnection) url.openConnection();
InputStream isr = httpcon.getInputStream();
try (BufferedReader bw = new BufferedReader(new InputStreamReader(isr, "utf-8"))) {
StringBuilder sb = new StringBuilder();
String line;
while ((line = bw.readLine()) != null) { // read whole response
sb.append(line);
}
System.out.println(sb); //Output whole response into console or use logger of your choice instead of System.out.println
}
I want to get the json object from the given url which provides a downloadable link for the *.json file.
The *.json file contains one json object in it.
I have tried the following code with each I could read the *.json file as a string but when I convert it into a json object it throws an exception.
URL url = new URL(fileurl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = br.readLine();
while (line != null)
{
sb.append(line);
line = br.readLine();
}
result = sb.toString();
JSONObject json = new JSONObject(result);`
I dont want to use org.json.simple library.
is there any other way it could be achieved like using org.json lib
URL obj = new URL(<url>);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("GET");
con.setRequestProperty("User-Agent", "Mozilla/5.0");
con.setRequestProperty("Accept", "application/json");
int responseCode = con.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
BufferedReader in = new BufferedReader(new InputStreamReader(
con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
JSONObject jsonObject = new JSONObject(response.toString());
This is using the org.json:json. This works for me.
If using org.json.simple library is your problem then there are many other libraries available in java
You can try using the Gson Library by google.
From : https://github.com/google/gson
Gson is a Java library that can be used to convert Java Objects into
their JSON representation. It can also be used to convert a JSON
string to an equivalent Java object. Gson can work with arbitrary Java
objects including pre-existing objects that you do not have
source-code of.
There are a few open-source projects that can convert Java objects to
JSON. However, most of them require that you place Java annotations in
your classes; something that you can not do if you do not have access
to the source-code. Most also do not fully support the use of Java
Generics. Gson considers both of these as very important design goals.
Searching up on google I found this solution to read json strings from URL:
JSONObject json = new JSONObject(IOUtils.toString(new URL("https://somelink.com"), Charset.forName("UTF-8")));
The problem is that there is no JSONObject(String) constructor, why is that?
I thin you use google-gson, use org.json, there is constructor:
JSONObject obj = new JSONObject(str);
String myData = obj.getString("myData");
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