2017-11-30 8 views
0

이 API의 특정 데이터를 가져와 http://countryapi.gear.host/v1/Country/getCountries?pName=Australia으로 가져와이를 String으로 변환하고 콘솔에 써야합니다. 나는 호주에 대해서만 자료를 얻고 싶다. Name과 Alpha2Code에 대해서만 String 형식의 데이터를 어떻게 얻을 수 있습니까 : Australia, AU? EntityUtils.toString(response)을 사용하려했지만 작동하지 않습니다.REST API를 사용하여 웹 서비스에서 데이터 수신

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); 
} 
} 

코드는 실제로이 같은 호주 JSON을 반환 :

enter image description here

+0

내가 제대로 이해하고있는 경우, 서비스가 JSON 응답을 반환하고 해당 응답을 인쇄해야 문자열로. 간단히 json 응답을 구문 분석하고 json 응답의 필수 키/값을 인쇄 할 수 있습니다. – Rahul

+0

네, String과 같은 두 개의 매개 변수 (Name과 alpha2Code)에 대해서만 json 응답을 인쇄해야합니다. 어떻게해야합니까? – Viola

답변

0

이 같은 시도 : 당신은 URL 아래에 더에 JSON 구문 분석 API를 탐색 할 수 있습니다

Gson gson = new Gson(); 
JsonObject result = gson.fromJson(line, JsonObject.class); 
JsonArray response = result.getAsJsonArray("Response"); 
Country country = gson.fromJson(response, Country.class); 
+0

사용 방법을 모르겠습니다. Gson, JsonObject, JsonArray와 같은 클래스가 없습니다. – Viola

+0

maven을 사용하는 경우 다음을 확인하십시오. https://mvnrepository.com/artifact/com.google.code.gson/gson/2.8.2 – Leonardo

0

당신은 JSON 구문 분석을위한 자바 API를 사용할 수 있습니다

이 내 코드입니다. 나는 샘플 코드를 작성하는 중이다. 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("-----------"); 
}