【问题标题】:Java Reading From JSONJava 从 JSON 读取
【发布时间】:2018-10-15 13:58:52
【问题描述】:

我希望从我在 Netbeans Java 项目中使用的这个天气 API 获取天气到我自己的 Maven API 中,这一切正常,但是当我想将它分解成更小的可读时返回一个巨大的 JSON 响应文本。

我的代码正在返回:

{"coord":{"lon":-6.26,"lat":53.35},"天气":[{"id":801,"ma​​in":"云","description":"几 云","icon":"02d"}],"base":"stations","ma​​in":{"temp":285.59,"pressure": 1015,"湿度":58,"temp_min":285.15,"temp_max":286.15},"能见度":10000,"风":{"速度":3.6,"度":80},"云":{ "all":20},"dt":1539610200,"sys":{"type":1,"id":5237,"message":0.0027,"country":"IE","sunrise":1539586357, "日落":1539624469},"id":2964574,"name":"都柏林","cod":200}

我希望它能够返回,主要是天气和温度。如果有人有任何想法,请告诉我。附上代码。

public class WeatherInfo {
     public static String getWeather(String city) {
        String weather;
        String getUrl = "http://api.openweathermap.org/data/2.5/weather?q="+ city +"&appid=xxx";
        Client client = Client.create();
        WebResource target = client.resource(getUrl);

        ClientResponse response = target.get(ClientResponse.class);
        weather = response.getEntity(String.class);
        return weather;
}
}

【问题讨论】:

  • 你所说的“主要天气和天气温度”是什么意思?你能给出想要的json吗?
  • @noobCoder 更新了我上面的 JSON 并加粗了我希望能够读取/输出的内容,现在我可以使用 json 对象作为 main 然后使用 toDouble 查看 main - temp对于温度,但我无法查看天气 - 主要
  • 好的,如果我发布的答案对您有用,请告诉我。

标签: java rest


【解决方案1】:

我假设您希望从 getWeather 获得的返回值是 {"main":"Clouds","temp":285.59} 这是一个解决方案 - 在你的 pom 中添加杰克逊依赖

 <dependency>
  <groupId>com.fasterxml.jackson.core</groupId>
  <artifactId>jackson-databind</artifactId>
  <version>2.8.7</version>
</dependency>

这里有一个去掉其他细节只返回main和temp的方法,你可以编辑这个方法来添加更多的字段。

private static String getLessWeather(String weatherJson) throws IOException {
  Map<String, Object> lessWeatherMap = new LinkedHashMap<String, Object>();
  Map<String,Object> weatherMap = new ObjectMapper().readValue(weatherJson, LinkedHashMap.class);
  String main = (String) ((LinkedHashMap)((ArrayList)weatherMap.get("weather")).get(0)).get("main");
  lessWeatherMap.put("main", main);
  Double temp = (Double)((LinkedHashMap)weatherMap.get("main")).get("temp");
  lessWeatherMap.put("temp", temp);
  return new ObjectMapper().writeValueAsString(lessWeatherMap);
}

【讨论】:

    【解决方案2】:

    您需要使用库来解析 JSON 响应。这是一个带有很好示例和参考的 SO 问题:How to parse JSON in Java

    用户 SDekov 的回答列出了三个不错的选择:

    • 谷歌 GSON
    • 组织.JSON
    • 杰克逊

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-26
      • 1970-01-01
      • 1970-01-01
      • 2022-10-24
      • 1970-01-01
      相关资源
      最近更新 更多