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();
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");
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());
I am trying to modify my code without using buffered reader writer and stream method. can anyone suggest me how to simplify my code.
I am running this code in cucumber and it is running fine.
public String creatProduct() throws Throwable {
String payload = "{"
+ "\"productName\":\"Macroon\","
+ "\"productCode\":\"\","
+ "\"externalRoomId\":\"\","
+ "\"description\":\"\""
+ "}";
String requestUrl = "www.example.com";
try {
URL url = new URL(requestUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setRequestMethod("POST");
connection.setRequestProperty("Accept", "application/json");
connection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream(), "UTF-8");
writer.write(payload);
writer.close();
BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line;
while ((line = br.readLine()) != null) {
jsonString.append(line);
}
br.close();
connection.disconnect();
System.out.println("Response==>" + jsonString.toString());
Map<String, String> map = new HashMap<String, String>();
ObjectMapper mapper = new ObjectMapper();
System.out.println("Input payload:" + payload);
map = mapper.readValue(jsonString.toString(), new TypeReference<HashMap<String, String>>() {
});
System.out.println("Output Map: " + map);
map.get("productName");
assertEquals("Macroon", map.get("productName"));
} catch (Exception e) {
throw new RuntimeException(e.getMessage());
}
return jsonString.toString();
}
I have modified my code and it is working!
HttpClient httpclient = new HttpClient();
PostMethod post = new PostMethod("www.example.com");
post.setRequestEntity(new StringRequestEntity(payload, "application/json", null));
httpclient.executeMethod(post);
String jsonResponse = post.getResponseBodyAsString();
System.out.println("Response==>"+jsonResponse);
Map<String,String> map1 = new HashMap<String,String>();
ObjectMapper mapper=new ObjectMapper();
System.out.println("Input payload:"+ payload);
map1 = mapper.readValue(jsonResponse, new TypeReference<HashMap<String, String>>(){});
System.out.println("Output Map: "+map1);
map1.get("message");
assertEquals("Success",map1.get("message"));
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);
}
First the: Android Code
public class MachineController extends AsyncTask<String, String,List<Machine>> {
private static String REST_URL = "...";
List<Machine> machines;
#Override
protected List<Machine> doInBackground(String... params) {
machines = new ArrayList<Machine>();
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(REST_URL);
httpGet.addHeader("accept", "application/json");
HttpResponse response;
try {
response = httpClient.execute(httpGet);
HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream instream = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(instream));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
sb.append(line + "n");
String result = sb.toString();
Gson gson = new Gson();
JsonReader jsonReader = new JsonReader(new StringReader(result));
jsonReader.setLenient(true);
JsonParser parser = new JsonParser();
JsonArray jsonArray = parser.parse(jsonReader).getAsJsonArray();
for (JsonElement obj : jsonArray) {
Machine machine = gson.fromJson(obj.getAsJsonObject().get("mobileMachine"), Machine.class);
machines.add(machine);
machines.get(0);
}
instream.close();
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return machines;
}
}
Here is some Code of the JSON File
[
{ "mobileMachine":
{ "condition":"VERY_GOOD",
"document":"", . . .
"mobileCategory": { "idNr":"1816e5697eb3e0c8442786be5274cb05cff04c06b4338467c8679770bff32313f7f372b5ec2f7527dad0de47d0fb117e",
"mobileCategoryEng":"Bookletmaker",
"mobileCategoryGer":"Broschuerenfertigung" },
"modelYear":2006,
Abmessungen: 665x810mm " } }
{ "mobileMachine":
{
"condition":"VERY_GOOD"," ...... } } ]
Sometimes there is a mobileCategory inside. The mobileCategoryGer and mobileCategoryEng are allways null in the List.
I can't edit the JSON File! I only want the value for mobileCategoryGer and mobileCategoryEng from the Json File. The Rest works fine. I hope u understand and can help me to parse it correctly.
(Sorry for my english)
Here you go.
Type listType = new TypeToken<List<Machine>>() {}.getType();
ArrayList<Result> results = gson.fromJson(result, listType);
Here is your complete modified code:
public class MachineController extends AsyncTask<String, String,List<Machine>> {
private static String REST_URL = "...";
List<Machine> machines;
#Override
protected List<Machine> doInBackground(String... params) {
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(REST_URL);
httpGet.addHeader("accept", "application/json");
HttpResponse response;
try {
response = httpClient.execute(httpGet);
HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream instream = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(instream));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
sb.append(line + "n");
String result = sb.toString();
Gson gson = new Gson();
Type listType = new TypeToken<List<Machine>>() {}.getType();
machines= gson.fromJson(result, listType);
instream.close();
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return machines;
}
You could check if it has the key with has() method. Also you can get optional value with optJSONObject() and check if it is not null.
JsonArray jsonArray = parser.parse(jsonReader).getAsJsonArray();
try {
doSomething(jsonArray);
} catch (JSONException e) {
Log.wtf("Terrible Failure", e);
}
private void doSomething(JsonArray jsonArray) throws JSONException{
for (int i=0; i<jsonArray.length(); i++){
JSONObject obj = jsonArray.getJSONObject(i);
JSONObject mobileCategory = obj.optJSONObject("mobileCategory");
if(mobileCategory !=null){
if(mobileCategory.has("mobileCategoryEng") && mobileCategory.has("mobileCategoryGer") ){
String mobileCategoryEng = mobileCategory.getString("mobileCategoryEng");
String mobileCategoryGer = mobileCategory.getString("mobileCategoryGer");
}
}
}
}