Handling a Json API response with java - java

I've been trying to figure out how to handle the json response from a GET request. This is the code I have for the request:
String urlString = URL I want to request;
URL url = new URL(urlString);
URLConnection conn = url.openConnection();
InputStream is = conn.getInputStream();
String response = getStringFromInputStream(is);
My question is what to do now. I've been playing with gson but I cannot figure out how to parse the response for the required information.
I also found this method somewhere online to turn the response into a string:
private static String getStringFromInputStream(InputStream is) {
BufferedReader br = null;
StringBuilder sb = new StringBuilder();
String line;
try {
br = new BufferedReader(new InputStreamReader(is));
while ((line = br.readLine()) != null) {
sb.append(line);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return sb.toString();
}
If anyone could help me parse the string or somehow otherwise handle the response I'd really appreciate it.

You can use Jackson framework to parse the response into Java Object. Once you add the dependency, this is how it will work:
Let's say you are getting the below response from the API:
{
"id": 1,
"name": "foo"
}
You can write the following code to deserialise it into an Object:
public class Response {
private int id;
private String name;
//Getters and Setters
}
//code to convert
String response = sb.toString();
ObjectMapper mapper = new ObjectMapper();
Response responseObject = mapper.readValue(response, Response.class);
If the json is not valid, it will fail and throw JsonParseException or JsonMappingException. You can handle it in your code and respond accordingly.
Here's step by step tutorial on how to use Jackson.

It depends on the what you want to do with Json.I am assuming you want to convert in into an Java object.
For that you can use Gson or Jackson.
Suppose you have a json like
{"userId":"1","userName":"Yasir"}
and your java class like
class User{
int userId;
String userName;
//setters and getters
}
then you can use something like
Gson gson = new Gson();
User user= gson.fromJson(jsonInString, User.class);
to create java object.

Related

How to get json the data from json based api without using any 3rd party library in Android?

I want to fetch the json data from web api, I was previously using Retrofit for that, but I don't wanna use any third party library.
I know I can use HttpURLConnection or HttpClient but there is no proper post for that and they are too old, and in some post they were telling that it is deprecated, so if you have any other solution using HttpUrlConnection and HttpClient or without using that then please let me know.
And please tell me how to parse that data cause before that I was using GSONParser library for that.
Here is my example api:
https://www.mocky.io/v2/5b8126543400005b00ecb2fe
Hey you can retrieve your data using your methods, that depends on you. For example, I have never used a third party library to retrieve data from the server.
Think about this: a class that I can name FileContentReader with a method getContentFromUrl this will fetch your JSON data as string that you can then parse using JSONObject or JSONArray according to your file structure.
public class FileContentReader {
private Context appContext;
public FileContentReader(Context context){
this.appContext=context;
}
public String getContentFromUrl(String url)
{
StringBuilder content = new StringBuilder();
try {
URL u = new URL(url);
HttpURLConnection uc = (HttpURLConnection) u.openConnection();
if (uc.getResponseCode()==HttpURLConnection.HTTP_OK) {
InputStream is = uc.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));
String line;
while ((line = br.readLine()) != null) {
content.append(line).append("\n");
}
}else{
throw new IOException(uc.getResponseMessage());
}
} catch(StackOverflowError | Exception s){
s.printStackTrace();
} catch(Error e){
e.printStackTrace();
}
return content.toString();
}
}
You can use the code this way inside an asynchronous task or any background task :
FileContentReader fcr= new FileContentReader(getApplicationContext());
String data= fcr.getContentFromUrl("myurl");
if(!data.isEmpty())
{
try{
JSONArray ja = new JSONArray(data);
//... ou can then access and manupilate your data the way you want
}catch(JSONException e)
{
e.printStackTrace();}
}

Request to web services restful with pojo object and method post

I created a restful web service:
#POST
#Path("grd")
#Consumes("application/json")
#Produces("text/plain")
public String guardarDato(PostParams jsonObject) {
/*
something here
}
PostParams is a pojo:
public class PostParams {
private final Map<String, String> postParamsList;
public PostParams() {
postParamsList = new HashMap<>();
}
public void addParameter(String name, String value) {
postParamsList.put(name, value);
}
public String getPostParamsList(String name) {
return postParamsList.get(name);
}
public void getPostParamsMap() {
if (postParamsList.isEmpty()) {
System.out.println("Parametros vacios");
} else {
for (String key : postParamsList.keySet()) {
System.out.println("Clave: " + key + " -> Valor: " + postParamsList.get(key));
}
}
}
}
I am trying to call this web service from android with HttpUrlConnection,
but my object is null pojo in my web services.
try {
URL url = new URL("http://localhost:8080/VfqCh/hgt/opli/grd");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json");
// conn.setRequestProperty("Accept", "application/json");
PostParams postParams = new PostParams();
postParams.addParameter("h", "51rt3");
postParams.addParameter("x", "dsfsd8698sdfs");
postParams.addParameter("ax", "Dairon");
postParams.addParameter("tf", "D");
// String input = "{\"qty\":100,\"name\":\"iPad 4\"}";
Gson gson = new Gson();
String gString = gson.toJson(postParams, PostParams.class);
try (OutputStreamWriter printout = new OutputStreamWriter(conn.getOutputStream())) {
printout.write(gString);
printout.flush();
}
if (conn.getResponseCode() != HttpURLConnection.HTTP_OK) {
throw new RuntimeException("Failed : HTTP error code : "
+ conn.getResponseCode());
}
BufferedReader br = new BufferedReader(new InputStreamReader(
(conn.getInputStream())));
String output;
System.out.println("Output from Server .... \n");
while ((output = br.readLine()) != null) {
System.out.println(output);
}
conn.disconnect();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
The information is send to web services but the object is null.
if I change the type of object that is receive in the web services if it works!:
#POST
#Path("grd")
#Consumes("application/json")
#Produces("text/plain")
public String guardarDato(String jsonObject) {
/*
something here
}
But i need receive an object in the web services! It is possible?
You made a POJO for a HashMap, but you could have just used a JsonObject that is already provided by Gson and basically acts like a HashMap. Then, you toString it, and you have a JSON string you can send to a server. There is no need for Gson.toJson and worrying if it was converted correctly.
Your server is accepting a JSON string, as defined by
#Consumes("application/json")
Therefore, this should be the method
public String guardarDato(String jsonObject) {
You will need to add Gson as a dependency for your server, then you should be able to get the JSON to an object with something like PostParams params = Gson.fromJson(jsonObject, PostParams.class) assuming the data was sent correctly from the client side, but as stated earlier, your POJO doesn't add much functionality on top of just a JsonObject or plain HashMap

Get json object created in mvc (jsonResult) in android

I created a json result in mvc and I'm building an Android app to get the json result. This is what my json result looks like
{"name":"Mr. Spock","gender":"Male"}
This is my controller
public ActionResult Index()
{
var result = new { name = "Mr. Spock", gender = "Male" };
return Json(result, JsonRequestBehavior.AllowGet);
}
And this I'm using in android
// Creating JSON Parser instance
JSONParser jParser = new JSONParser();
// getting JSON string from URL
JSONObject json = jParser.getJSONFromUrl(url);
JSONParser class
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
public JSONObject getJSONFromUrl(String url) {
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
I have a declared variable url. Every time I debug, the json variable does not have any values and says "errors during the evaluation"
Anyone with a tip? I tried working with Gson, but no succes
Kind regards
I'll give you some code for Gson. It really is much easier to work with than the built in JSON parsing code. Here's a minimal example using your JSON.
Person.class:
package com.example.tutorial.models;
import com.google.gson.annotations.SerializedName;
public class Person {
#SerializedName("gender")
public String gender = "";
#SerializedName("name")
public String name = "";
}
The annotations are really only necessary when your variable and JSON name differ, but I tend to always include them as it reinforces that they are coming from JSON.
To deserialize:
Gson gson = new GsonBuilder().create();
Person person = gson.fromJson(json, Person.class);
It really is that simple. If this does not work, log the result from the web server and make sure it really is the valid JSON string you expect it to be.
I do have one question, where is your AsyncTask? Your attempt to open a connection to the webserver in the UI thread will definitely cause a NetworkOnMainThreadException. I created a library to do RESTful calls on Android. It's licensed under BSD, so feel free to use it as a guide or outright use it: https://github.com/nedwidek/Android-Rest-API

Reading line from website

I am making a little program thath will read data from website. String in the html file is already managed every info is divided with ; . Now i should read complete line here is example of this line:
14:47;24.02.12;18.7°C;18.7°C;285;0.5m/s; 6:48;17:37; Warm ;36;1.8;0.0;
So first how should i read them with HTTP Get or is there anything other? And then i would like to save each info, they are seperated with ; into a variable. And how should i cut each info from this line.
You definitely need to do some homework, but this methods will help you:
public static String getContentFromUrl(String url) throws ClientProtocolException, IOException {
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
HttpResponse response;
response = httpClient.execute(httpGet);
HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream inStream = entity.getContent();
String result = HttpService.convertStreamToString(inStream);
inStream.close();
return result;
}
return null;
}
private static String convertStreamToString(InputStream is) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
This allows you to get data from a URL. Then lookup String.split to chop your string into usable entities.
Hope this helps!
Use GET request to fetch the data from the website
Separate the string-data from the HTML-markup
Parse the string into multiple strings or a list of strings, using ';' as the delimiter.
Android Java SDK String reference

Parsing JSON from URL

Is there any simplest way to parse JSON from a URL? I used Gson I can't find any helpful examples.
First you need to download the URL (as text):
private static String readUrl(String urlString) throws Exception {
BufferedReader reader = null;
try {
URL url = new URL(urlString);
reader = new BufferedReader(new InputStreamReader(url.openStream()));
StringBuffer buffer = new StringBuffer();
int read;
char[] chars = new char[1024];
while ((read = reader.read(chars)) != -1)
buffer.append(chars, 0, read);
return buffer.toString();
} finally {
if (reader != null)
reader.close();
}
}
Then you need to parse it (and here you have some options).
GSON (full example):
static class Item {
String title;
String link;
String description;
}
static class Page {
String title;
String link;
String description;
String language;
List<Item> items;
}
public static void main(String[] args) throws Exception {
String json = readUrl("http://www.javascriptkit.com/"
+ "dhtmltutors/javascriptkit.json");
Gson gson = new Gson();
Page page = gson.fromJson(json, Page.class);
System.out.println(page.title);
for (Item item : page.items)
System.out.println(" " + item.title);
}
Outputs:
javascriptkit.com
Document Text Resizer
JavaScript Reference- Keyboard/ Mouse Buttons Events
Dynamically loading an external JavaScript or CSS file
Try the java API from json.org:
try {
JSONObject json = new JSONObject(readUrl("..."));
String title = (String) json.get("title");
...
} catch (JSONException e) {
e.printStackTrace();
}
GSON has a builder that takes a Reader object: fromJson(Reader json, Class classOfT).
This means you can create a Reader from a URL and then pass it to Gson to consume the stream and do the deserialisation.
Only three lines of relevant code.
import java.io.InputStreamReader;
import java.net.URL;
import java.util.Map;
import com.google.gson.Gson;
public class GsonFetchNetworkJson {
public static void main(String[] ignored) throws Exception {
URL url = new URL("https://httpbin.org/get?color=red&shape=oval");
InputStreamReader reader = new InputStreamReader(url.openStream());
MyDto dto = new Gson().fromJson(reader, MyDto.class);
// using the deserialized object
System.out.println(dto.headers);
System.out.println(dto.args);
System.out.println(dto.origin);
System.out.println(dto.url);
}
private class MyDto {
Map<String, String> headers;
Map<String, String> args;
String origin;
String url;
}
}
If you happen to get a 403 error code with an endpoint which otherwise works fine (e.g. with curl or other clients) then a possible cause could be that the endpoint expects a User-Agent header and by default Java URLConnection is not setting it. An easy fix is to add at the top of the file e.g. System.setProperty("http.agent", "Netscape 1.0");.
You could use org.apache.commons.io.IOUtils for downloading and org.json.JSONTokener for parsing:
JSONObject jo = (JSONObject) new JSONTokener(IOUtils.toString(new URL("http://gdata.youtube.com/feeds/api/videos/SIFL9qfmu5U?alt=json"))).nextValue();
System.out.println(jo.getString("version"));
Here is a easy method.
First parse the JSON from url -
public String readJSONFeed(String URL) {
StringBuilder stringBuilder = new StringBuilder();
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(URL);
try {
HttpResponse response = httpClient.execute(httpGet);
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
if (statusCode == 200) {
HttpEntity entity = response.getEntity();
InputStream inputStream = entity.getContent();
BufferedReader reader = new BufferedReader(
new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null) {
stringBuilder.append(line);
}
inputStream.close();
} else {
Log.d("JSON", "Failed to download file");
}
} catch (Exception e) {
Log.d("readJSONFeed", e.getLocalizedMessage());
}
return stringBuilder.toString();
}
Then place a task and then read the desired value from JSON -
private class ReadPlacesFeedTask extends AsyncTask<String, Void, String> {
protected String doInBackground(String... urls) {
return readJSONFeed(urls[0]);
}
protected void onPostExecute(String result) {
JSONObject json;
try {
json = new JSONObject(result);
////CREATE A JSON OBJECT////
JSONObject data = json.getJSONObject("JSON OBJECT NAME");
////GET A STRING////
String title = data.getString("");
//Similarly you can get other types of data
//Replace String to the desired data type like int or boolean etc.
} catch (JSONException e1) {
e1.printStackTrace();
}
//GETTINGS DATA FROM JSON ARRAY//
try {
JSONObject jsonObject = new JSONObject(result);
JSONArray postalCodesItems = new JSONArray(
jsonObject.getString("postalCodes"));
JSONObject postalCodesItem = postalCodesItems
.getJSONObject(1);
} catch (Exception e) {
Log.d("ReadPlacesFeedTask", e.getLocalizedMessage());
}
}
}
You can then place a task like this -
new ReadPlacesFeedTask()
.execute("JSON URL");
public static TargetClassJson downloadPaletteJson(String url) throws IOException {
if (StringUtils.isBlank(url)) {
return null;
}
String genreJson = IOUtils.toString(new URL(url).openStream());
return new Gson().fromJson(genreJson, TargetClassJson.class);
}
import org.apache.commons.httpclient.util.URIUtil;
import org.apache.commons.io.FileUtils;
import groovy.json.JsonSlurper;
import java.io.File;
tmpDir = "/defineYourTmpDir"
URL url = new URL("http://yourOwnURL.com/file.json");
String path = tmpDir + "/tmpRemoteJson" + ".json";
remoteJsonFile = new File(path);
remoteJsonFile.deleteOnExit();
FileUtils.copyURLToFile(url, remoteJsonFile);
String fileTMPPath = remoteJsonFile.getPath();
def inputTMPFile = new File(fileTMPPath);
remoteParsedJson = new JsonSlurper().parseText(inputTMPFile.text);
I use java 1.8
with com.fasterxml.jackson.databind.ObjectMapper
ObjectMapper mapper = new ObjectMapper();
Integer value = mapper.readValue(new URL("your url here"), Integer.class);
Integer.class can be also a complex type. Just for example used.
A simple alternative solution:
Paste the URL into a json to csv converter
Open the CSV file in either Excel or Open Office
Use the spreadsheet tools to parse the data

Categories