我需要从此API http://countryapi.gear.host/v1/Country/getCountries?pName=Australia获取特定数据,将其转换为String并在控制台上写出。我想只为澳大利亚获取数据。如何只为Name和Alpha2Code获取String格式的数据,如下所示:
Australia, AU
?我试图使用EntityUtils.toString(response)
,但它不起作用。
这是我的代码:
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,如下所示:
答案 0 :(得分:0)
您可以使用java api进行json解析。我只是在写一个示例代码。你可以在下面的URL上探索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("-----------");
}
答案 1 :(得分:0)
尝试这样的事情:
Gson gson = new Gson();
JsonObject result = gson.fromJson(line, JsonObject.class);
JsonArray response = result.getAsJsonArray("Response");
Country country = gson.fromJson(response, Country.class);