With HTTPURLCONNECTION I am able to get the JSON response and using Writer I am able to save it to output.json file also. But I am not able to read the content of output.json or directly from the url "http://somesite.com/json/server.json" using GSON. I am facing few issues when using gson.
public class ConnectToUrlUsingBasicAuthentication {
public static void main(String[] args) {
try {
String webPage = "http://somesite.com/json/server.json";
//HTTPURLCONNECTION
URL url = new URL(webPage);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("Accept", "application/json");
StringBuilder sb = new StringBuilder();
InputStream is = conn.getInputStream();
InputStreamReader isr = new InputStreamReader(is,Charset.defaultCharset());
BufferedReader bufferedReader = new BufferedReader(isr);
String line;
while((line = bufferedReader.readLine()) != null) {
System.out.println("*** BEGIN ***");
try(Writer writer = new OutputStreamWriter(new FileOutputStream("Output.json") , "UTF-8")){
Gson gson = new GsonBuilder().create();
gson.toJson(line, writer);
System.out.println("Written successfully");
}
System.out.println(line);
System.out.println("*** END ***");
try(Reader reader = new InputStreamReader(is, "UTF-8")){
Gson gson = new GsonBuilder().create();
JsonData p = gson.fromJson(reader, JsonData.class);
System.out.println(p);
}
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
The other class I am passing during gson.fromjson call is Jsondata.
public class JsonData {
private String body;
private List<String> items = new ArrayList<String>();
private List<String> messages = new ArrayList<String>();
// Getters and setters are not required for this example.
// GSON sets the fields directly using reflection.
#Override
public String toString() {
return messages + " - " + items + " - " + messages ;
}
}
Outputs:
Json format (Is the JSON format looks fine or any syntax error is there in it)
line = {
"body":
{"items":[
{"name":"server","state":"RUNNING","health":"HEALTH_OK"},
{"name":"server1","state":"RUNNING","health":"HEALTH_OK"},
{"name":"server2","state":"RUNNING","health":"HEALTH_OK"}
]},
"messages":[]}
Value printed for variable p is null.
Could some one please help me in printing the Json response in variable p using Gson.
Wait until you've read the entire response body before you try and convert it with GSON.
try (Writer writer = new OutputStreamWriter(
new FileOutputStream("Output.json") , "UTF-8")) {
Gson gson = new GsonBuilder().create();
while((line = bufferedReader.readLine()) != null) {
gson.toJson(line, writer);
}
}
// Now read it.
try (Reader reader = new InputStreamReader(is, "UTF-8")){
Gson gson = new GsonBuilder().create();
JsonData p = gson.fromJson(reader, JsonData.class);
System.out.println(p);
}
Related
I am trying to collect a single piece of data from an API, that being the population of a certain country. Everything works properly except for cutting the population value out of the JSON.
{"Info":[{"area":301336,"nativeName":"Italia","capital":"Rome","demonym":"Italian","flag":"https://restcountries.eu/data/ita.svg","alpha2Code":"IT","languages":[{"nativeName":"Italiano","iso639_2":"ita","name":"Italian","iso639_1":"it"}],"borders":["AUT","FRA","SMR","SVN","CHE","VAT"],"subregion":"Southern Europe","callingCodes":["39"],"regionalBlocs":[{"otherNames":[],"acronym":"EU","name":"European Union","otherAcronyms":[]}],"gini":36,"population":60665551,"numericCode":"380","alpha3Code":"ITA","topLevelDomain":[".it"],"timezones":["UTC+01:00"],"cioc":"ITA","translations":{"br":"Itália","de":"Italien","pt":"Itália","ja":"イタリア","hr":"Italija","it":"Italia","fa":"ایتالیا","fr":"Italie","es":"Italia","nl":"Italië"},"name":"Italy","altSpellings":["IT","Italian Republic","Repubblica italiana"],"region":"Europe","latlng":[42.83333333,12.83333333],"currencies":[{"symbol":"\u20ac","code":"EUR","name":"Euro"}]}]}
Within the JSON, It is called "Population".
This is my user input code
public static String UserInputsDetails() {
System.out.println("Please input the country name");
Scanner in = new Scanner(System.in);
String Input = in.nextLine();
return Input;
}
This is my JSON Getter Code
public static JSONArray MakeConnection(String countryname) {
JSONArray JSON = null;
try {
String url = "https://restcountries.eu/rest/v2/name/" + countryname;
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
int responseCode = con.getResponseCode();
System.out.println("\nSending 'GET' request to URL : " + url);
System.out.println("Response Code : " + responseCode);
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
JSON = new JSONArray(response.toString());
} catch (Exception e) {
System.out.println(e);
}
return JSON;
}
This is my Result code, to get just the population
public static void PrintResult(JSONArray JSON){
String population = null;
try {
JSONObject jobj = new JSONObject();
jobj.put("Info", JSON);
population = jobj.getString("population");
System.out.println(jobj);
System.out.println(population);
} catch (Exception e) {
System.out.println(e);
}
}
And finally, this is my main
public static void main(String []args) {
String Input = UserInput.UserInputsDetails();
JSONArray JSON = Connection.MakeConnection(Input);
Result.PrintResult(JSON);
}
I get the error
org.json.JSONException: JSONObject["population"] not found.
What am I doing wrong?
Delete this part:
JSONObject jobj = new JSONObject();
jobj.put("Info", JSON);
population = jobj.getString("population");
System.out.println(jobj);
System.out.println(population);
JSON is already an array, why are you converting it into a JSONObject?
Change to something like this:
Long population = JSON.getJSONObject(0).getLong("population");
I got a JSON output. Now need to parse the JSON String.
Some part of my code:
int responseCode = con.getResponseCode();
System.out.println("\nSending 'POST' request to URL : " + url);
System.out.println("Post parameters : " + query_en);
System.out.println("Response Code : " + responseCode);
BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
//print result
System.out.println(response.toString());
How to parse the output using Java?
There are a lot of third party libs for parsing JSON in java. For example jackson:
private void test(BufferedReader reader) {
ObjectMapper mapper = new ObjectMapper();
try {
Map<String, Object> map = mapper.readValue(reader, new TypeReference<Map<String, String>>() {
});
System.out.println(map);
} catch (IOException e) {
e.printStackTrace();
}
}
Gson:
private void test2(BufferedReader r) {
Gson gson = new Gson();
Type type = new TypeToken<Map<String, String>>(){}.getType();
Map<String, String> myMap = gson.fromJson(r, type);
System.out.println(myMap);
}
You can use https://mvnrepository.com/artifact/com.google.code.gson/gson/2.8.0 for that.
JsonObject jsonData = new JsonParser().parse(response.toString()).getAsJsonObject();
Getting JSONObject from URL-Json source.
public class source02 {
public static void main(String[] args) {
try {
URL url = new URL("http://openapi.seoul.go.kr:8088/sample/json/StationDayTrnsitNmpr/1/5/");
InputStreamReader isr = new InputStreamReader(url.openConnection().getInputStream(), "UTF-8");
JSONObject object = (JSONObject)JSONValue.parse(isr);
JSONObject sdt = (JSONObject) object.get("StationDayTrnsitNmpr");
System.out.println(sdt.get("list_total_count").toString());
} catch (Exception e) {
e.printStackTrace();
}
}
}
and Json source
{"StationDayTrnsitNmpr":{"list_total_count":44,"RESULT":{"CODE":"INFO-000","MESSAGE":"정상 처리되었습니다"},"row":[{"SN":"1","STATN_NM":"신도림","WKDAY":333873.0,"SATDAY":298987.0,"SUNDAY":216886.0},{"SN":"2","STATN_NM":"동대문역사문화공원","WKDAY":251049.0,"SATDAY":211456.0,"SUNDAY":150589.0},{"SN":"3","STATN_NM":"충무로","WKDAY":229882.0,"SATDAY":194865.0,"SUNDAY":142150.0},{"SN":"4","STATN_NM":"종로3가","WKDAY":224539.0,"SATDAY":196606.0,"SUNDAY":142525.0},{"SN":"5","STATN_NM":"사당","WKDAY":200985.0,"SATDAY":180230.0,"SUNDAY":134354.0}]}}
getting java.lang.NullPointerException
at api.source02.main(source02.java:16)
Well this is working for me
URL url = new URL("http://openapi.seoul.go.kr:8088/sample/json/StationDayTrnsitNmpr/1/5/");
InputStreamReader isr = new InputStreamReader(url.openConnection().getInputStream(), "UTF-8");
BufferedReader br = new BufferedReader(isr);
StringBuilder response = new StringBuilder();
for (String line = br.readLine(); line != null; line = br.readLine()) {
response.append(line);
}
JSONObject object = new JSONObject(response.toString());
JSONObject sdt = (JSONObject) object.get("StationDayTrnsitNmpr");
System.out.println(sdt.get("list_total_count").toString());
Made an app to translate different words to different Language
Using Yandex converter getting proper results on Browser
converting Kiss
RESULTS as JSON object is
{"code":200,"lang":"en-hi","text":["चुम्बन"]} //proper
but while getting result on app
RESULT
{"code":200,"lang":"en-hi","text":["à¤à¥à¤®à¥à¤¬à¤¨"]}
JSONParser jParser = new JSONParser();
// get json string from url
JSONObject json = jParser.getJSONFromUrl(yourJsonStringUrl);
geJSONFromUrl function
public JSONObject getJSONFromUrl(String urlSource) {
//make HTTP request
try {
URL url = new URL(urlSource);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setDoOutput(true);
urlConnection.setChunkedStreamingMode(0);
inputStream = new BufferedInputStream(urlConnection.getInputStream());
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
//Read JSON data from inputStream
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
inputStream.close();
json = sb.toString();
} catch (Exception e) {
Log.e(TAG, "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e(TAG, "Error parsing data " + e.toString());
}
return jObj;// return JSON String
}
}
Is there any way i can get proper results?
Please HelpRegards
changed
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "iso-8859-1"), 8);
to
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
I am doing basic http auth with the HttpURLConnection object in Java.
URL urlUse = new URL(url);
HttpURLConnection conn = null;
conn = (HttpURLConnection) urlUse.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("Content-length", "0");
conn.setUseCaches(false);
conn.setAllowUserInteraction(false);
conn.setConnectTimeout(timeout);
conn.setReadTimeout(timeout);
conn.connect();
if(conn.getResponseCode()==201 || conn.getResponseCode()==200)
{
success = true;
}
I am expecting a JSON object, or string data in the format of a valid JSON object, or HTML with simple plain text that is valid JSON. How do I access that from the HttpURLConnection after it returns a response?
You can get raw data using below method. BTW, this pattern is for Java 6. If you are using Java 7 or newer, please consider try-with-resources pattern.
public String getJSON(String url, int timeout) {
HttpURLConnection c = null;
try {
URL u = new URL(url);
c = (HttpURLConnection) u.openConnection();
c.setRequestMethod("GET");
c.setRequestProperty("Content-length", "0");
c.setUseCaches(false);
c.setAllowUserInteraction(false);
c.setConnectTimeout(timeout);
c.setReadTimeout(timeout);
c.connect();
int status = c.getResponseCode();
switch (status) {
case 200:
case 201:
BufferedReader br = new BufferedReader(new InputStreamReader(c.getInputStream()));
StringBuilder sb = new StringBuilder();
String line;
while ((line = br.readLine()) != null) {
sb.append(line+"\n");
}
br.close();
return sb.toString();
}
} catch (MalformedURLException ex) {
Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, ex);
} finally {
if (c != null) {
try {
c.disconnect();
} catch (Exception ex) {
Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, ex);
}
}
}
return null;
}
And then you can use returned string with Google Gson to map JSON to object of specified class, like this:
String data = getJSON("http://localhost/authmanager.php");
AuthMsg msg = new Gson().fromJson(data, AuthMsg.class);
System.out.println(msg);
There is a sample of AuthMsg class:
public class AuthMsg {
private int code;
private String message;
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
JSON returned by http://localhost/authmanager.php must look like this:
{"code":1,"message":"Logged in"}
Regards
Define the following function (not mine, not sure where I found it long ago):
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();
}
Then:
String jsonReply;
if(conn.getResponseCode()==201 || conn.getResponseCode()==200)
{
success = true;
InputStream response = conn.getInputStream();
jsonReply = convertStreamToString(response);
// Do JSON handling here....
}
In addition, if you wish to parse your object in case of http error (400-5** codes),
You can use the following code: (just replace 'getInputStream' with 'getErrorStream':
BufferedReader rd = new BufferedReader(
new InputStreamReader(conn.getErrorStream()));
StringBuilder sb = new StringBuilder();
String line;
while ((line = rd.readLine()) != null) {
sb.append(line);
}
rd.close();
return sb.toString();
The JSON string will just be the body of the response you get back from the URL you have called. So add this code
...
BufferedReader in = new BufferedReader(new InputStreamReader(
conn.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null)
System.out.println(inputLine);
in.close();
That will allow you to see the JSON being returned to the console. The only missing piece you then have is using a JSON library to read that data and provide you with a Java representation.
Here's an example using JSON-LIB
This function will be used get the data from url in form of HttpResponse object.
public HttpResponse getRespose(String url, String your_auth_code){
HttpClient client = new DefaultHttpClient();
HttpPost postForGetMethod = new HttpPost(url);
postForGetMethod.addHeader("Content-type", "Application/JSON");
postForGetMethod.addHeader("Authorization", your_auth_code);
return client.execute(postForGetMethod);
}
Above function is called here and we receive a String form of the json using the Apache library Class.And in following statements we try to make simple pojo out of the json we received.
String jsonString =
EntityUtils.toString(getResponse("http://echo.jsontest.com/title/ipsum/content/ blah","Your_auth_if_you_need_one").getEntity(), "UTF-8");
final GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.registerTypeAdapter(JsonJavaModel .class, new CustomJsonDeserialiser());
final Gson gson = gsonBuilder.create();
JsonElement json = new JsonParser().parse(jsonString);
JsonJavaModel pojoModel = gson.fromJson(
jsonElementForJavaObject, JsonJavaModel.class);
This is a simple java model class for incomming json.
public class JsonJavaModel{
String content;
String title;
}
This is a custom deserialiser:
public class CustomJsonDeserialiserimplements JsonDeserializer<JsonJavaModel> {
#Override
public JsonJavaModel deserialize(JsonElement json, Type type,
JsonDeserializationContext arg2) throws JsonParseException {
final JsonJavaModel jsonJavaModel= new JsonJavaModel();
JsonObject object = json.getAsJsonObject();
try {
jsonJavaModel.content = object.get("Content").getAsString()
jsonJavaModel.title = object.get("Title").getAsString()
} catch (Exception e) {
e.printStackTrace();
}
return jsonJavaModel;
}
Include Gson library and org.apache.http.util.EntityUtils;