0

I need to get specific data from this API http://countryapi.gear.host/v1/Country/getCountries?pName=Australia, convert it to String and write out on the console. I want to get data only for Australia. How can I get data in String format only for Name and Alpha2Code like this: Australia, AU? I was trying to use EntityUtils.toString(response) but it doesn't work.

This is my code:

public class Client {

public static void main(String[] args) throws ClientProtocolException, IOException {

    HttpClient client = new DefaultHttpClient();
    HttpGet request = new HttpGet("http://countryapi.gear.host/v1/Country/getCountries?pName=Australia");
    request.addHeader("accept", "application/json");
    HttpResponse response = client.execute(request);
    HttpEntity entity = response.getEntity();
    InputStream stream = entity.getContent();
    BufferedReader reader = new BufferedReader(new InputStreamReader(stream));
    String line = reader.readLine();
    System.out.println(line);
}
}

The code actually return JSON for Australia, like this:

enter image description here

Viola
  • 487
  • 1
  • 10
  • 33
  • If I am understanding correctly, service is returning a json response and you need to print that response as string. You can simply parse the json response and print the required key/value of json response. – Rahul Nov 30 '17 at 19:37
  • yes, I need to print that json response as String, only for two parameters: Name and alpha2Code. How can I do this? – Viola Nov 30 '17 at 19:39

2 Answers2

0

You can use java api for json parsing. I am just writing a sample code. YOu can explore json parsing api more on below URL: http://www.oracle.com/technetwork/articles/java/json-1973242.html

JsonObject obj = rdr.readObject();
JsonArray results = obj.getJsonArray("data");
for (JsonObject result : results.getValuesAs(JsonObject.class)) {
    System.out.print(result.getJsonObject("name").getString("name"));
    System.out.print(": ");
    System.out.println(result.getString("message", ""));
    System.out.println("-----------");
 }
Rahul
  • 309
  • 1
  • 11
0

Try something like this:

Gson gson = new Gson();
JsonObject result = gson.fromJson(line, JsonObject.class);
JsonArray response = result.getAsJsonArray("Response");
Country country = gson.fromJson(response, Country.class);
Leonardo
  • 1,263
  • 7
  • 20
  • 51
  • I don't know how to use this. I don't have such classes as Gson, JsonObject, JsonArray. – Viola Nov 30 '17 at 20:53
  • If you're using maven, check this out: https://mvnrepository.com/artifact/com.google.code.gson/gson/2.8.2 – Leonardo Nov 30 '17 at 23:22