繁体   English   中英

从JSON读取Java

[英]Java Reading From JSON

我希望从我在Netbeans Java项目中使用的天气API中获取天气,并将其转换为我自己的Maven API,这一切都很好,但是当我想将其分解为较小的可读文本时,返回巨大的JSON响应。

我的代码当前正在返回:

{“ coord”:{“ lon”:-6.26,“ lat”:53.35},“ 天气 ”:[{“ id”:801,“ main ”:“ Clouds”,“ description”:“ F少量云”,“ icon“:” 02d“}],” base“:” stations“,” main “:{” temp “:285.59,” pressure“:1015,”湿度“:58,” temp_min“:285.15,” temp_max“: 286.15}, “可见性”:10000, “风”:{ “速度”:3.6, “DEG”:80}, “云”:{ “所有”:20}, “DT”:1539610200, “SYS”:{ “类型”:1, “ID”:5237, “消息”:0.0027, “国家”: “IE”, “日出”:1539586357, “日落”:1539624469}, “ID”:2964574, “姓名”:”都柏林”, “鳕鱼”: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;
}
}

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

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

您需要使用一个库来解析JSON响应。 这是一个带有出色示例和参考的SO问题: 如何在Java中解析JSON

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

  • Google GSON
  • Org.JSON
  • 杰克逊

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM