简体   繁体   中英

Java Reading From JSON

I am looking to get the weather from this weather API I am using in a Netbeans Java project into my own Maven API, this is all working fine but returning a huge chunky JSON response when I want to break it down into smaller readable text.

My code is currently returning:

{"coord":{"lon":-6.26,"lat":53.35}," weather ":[{"id":801," main ":"Clouds","description":"few clouds","icon":"02d"}],"base":"stations"," main ":{" temp ":285.59,"pressure":1015,"humidity":58,"temp_min":285.15,"temp_max":286.15},"visibility":10000,"wind":{"speed":3.6,"deg":80},"clouds":{"all":20},"dt":1539610200,"sys":{"type":1,"id":5237,"message":0.0027,"country":"IE","sunrise":1539586357,"sunset":1539624469},"id":2964574,"name":"Dublin","cod":200}

I would instead like it to be able to return, main in weather and temp in weather as well. If anyone has any ideas let me know. Code is attached.

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

I am assuming your desired return value from getWeather is {"main":"Clouds","temp":285.59} Here is a solution for that - add jackson dependency in your pom

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

And here is a method that strips out other details and returns only main and temp, you can edit this method to add more fields.

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

You need to use a library to parse the JSON response. Here is an SO question with great examples and references: How to parse JSON in Java

The answer from user SDekov lists three good options:

  • Google GSON
  • Org.JSON
  • Jackson

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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