简体   繁体   中英

how to convert json to a nested map with Gson

I am trying to convert a json string into a nested map. here is the json I am trying to convert:

{
  "coord": {
    "lon": -0.13,
    "lat": 51.51
  },
  "weather": [
    {
      "id": 803,
      "main": "Clouds",
      "description": "broken clouds",
      "icon": "04n"
    }
  ],
  "base": "stations",
  "main": {
    "temp": 280.83,
    "feels_like": 278.79,
    "temp_min": 279.15,
    "temp_max": 282.15,
    "pressure": 1006,
    "humidity": 87
  },
  "visibility": 10000,
  "wind": {
    "speed": 1.5
  },
  "clouds": {
    "all": 75
  },
  "dt": 1580086051,
  "sys": {
    "type": 1,
    "id": 1414,
    "country": "GB",
    "sunrise": 1580111217,
    "sunset": 1580143144
  },
  "timezone": 0,
  "id": 2643743,
  "name": "London",
  "cod": 200
}

what I would like to map into string, float pairs is the "main": {} section with

{
   "temp": 280.83,
   "feels_like": 278.79,
   "temp_min": 279.15,
   "temp_max": 282.15,
   "pressure": 1006,
   "humidity": 87
}

I have also made a WeatherConditions class that is able to convert the "id" and "name" successfully. The WeatherMain class is where I am attempting to fill the map. Here is the code for those classes:

public class WeatherConditions {
    int id;
    String name;
    HashMap<String, Float> main;

    public WeatherConditions(int id, String name, HashMap<String, Float> main) {
        this.id = id;
        this.name = name;
        this.main = main;

    }

    public static class WeatherMain {
        private static float temp;
        private static float pressure;
        private static float humidity;
        private static float temp_min;
        private static float temp_max;

        public WeatherMain( float temp, float pressure, float humidity, float temp_max, float temp_min ) {
            WeatherMain.temp = temp;
            WeatherMain.pressure = pressure;
            WeatherMain.humidity = humidity;
            WeatherMain.temp_max = temp_max;
            WeatherMain.temp_min = temp_min;
        }

        public static String displayWeatherMain() {
            String temperature;
            temperature = "Temp: " + temp + "\nPressure: " + pressure + "\nHumidity: " + humidity +
                    "\nTemp_max: " + temp_max + "\nTemp_min: " + temp_min;
            return temperature;
        }


    }

    public String displayWeatherConditions() {
        String temp;

        temp = "ID: " + id + "\nName: " + name + "\n" + WeatherMain.displayWeatherMain();
        return temp;

    }
}

In the main class I use this this function to parse the json string:


public static String parse(String responseBody) {
        Gson gson = new Gson();

        WeatherConditions newWeather = gson.fromJson(responseBody, WeatherConditions.class);

        System.out.println(newWeather.displayWeatherConditions());
        return null;
    }

my display is able to get the correct id and name but just gives me zeros for all the other values I am trying to convert. What is the correct way to do this?

I don't get why you want to use the HashMap and also why WeatherMain is static (static means that you don't need an instance, and this data seems to be from the instance).

Try replacing your WeatherConditions to this:

public class WeatherConditions {
    int id;
    String name;
    WeatherMain main;

    class WeatherMain {
        float temp;
        float feels_like;
        float temp_min;
        float temp_max;
        float pressure;
        float humidity;

        public String displayWeatherMain() {
            String temperature;
            temperature = "Temp: " + temp + "\nPressure: " + pressure + "\nHumidity: " + humidity +
                "\nTemp_max: " + temp_max + "\nTemp_min: " + temp_min;
            return temperature;
        }

        public HashMap<String, float> weatherMainAsHashMap() {
            HashMap res = new HashMap<String, float>();
            res.put("temp", temp);
            res.put("feels_like", feels_like);
            res.put("temp_min", temp_min);
            res.put("temp_max", temp_max);
            res.put("pressure", pressure);
            res.put("humidity", humidity);
            return res;
        }
    }

    public String displayWeatherConditions() {
        String temp;

        temp = "ID: " + id + "\nName: " + name + "\n" + main.displayWeatherMain();
        return temp;
    }
}

Now the Gson parse should work as the main type (WeatherMain) has the same properties as the json has and should also show the expected info.

MainClass.java

import com.google.gson.Gson;

public class MainClass {

    public static void main(String[] args) {
        try {
            Gson gson = new Gson();
            String responseBody = "{\"coord\":{\"lon\":-0.13,\"lat\":51.51},\"weather\":[{\"id\":803,\"main\":\"Clouds\",\"description\":\"broken clouds\",\"icon\":\"04n\"}],\"base\":\"stations\",\"main\":{\"temp\":280.83,\"feels_like\":278.79,\"temp_min\":279.15,\"temp_max\":282.15,\"pressure\":1006,\"humidity\":87},\"visibility\":10000,\"wind\":{\"speed\":1.5},\"clouds\":{\"all\":75},\"dt\":1580086051,\"sys\":{\"type\":1,\"id\":1414,\"country\":\"GB\",\"sunrise\":1580111217,\"sunset\":1580143144},\"timezone\":0,\"id\":2643743,\"name\":\"London\",\"cod\":200}";
            WeatherConditions newWeather = gson.fromJson(responseBody, WeatherConditions.class);
            System.out.println(
                    "Temp: " + newWeather.getMain().getTemp() + "\nPressure: " + newWeather.getMain().getPressure()
                            + "\nHumidity: " + newWeather.getMain().getHumidity() + "\nTemp_max: "
                            + newWeather.getMain().getTemp_max() + "\nTemp_min: " + newWeather.getMain().getTemp_min());
        } catch (Exception e) {
            System.out.println("Error" + e);
        }
    }
}

WeatherConditions.java

import lombok.Getter;

class WeatherConditions {
    @Getter
    private int id;
    @Getter
    private String name;
    @Getter
    private WeatherMain main;

    WeatherConditions() {
    }

    WeatherConditions(int id, String name, WeatherMain main) {
        this.id = id;
        this.name = name;
        this.main = main;
    }

    @Override
    public String toString() {
        return "WeatherConditions [id=" + id + ", name=" + name + ", main=" + main + ", getClass()=" + getClass()
                + ", hashCode()=" + hashCode() + ", toString()=" + super.toString() + "]";
    }

}

WeatherMain.java

import lombok.Getter;

public class WeatherMain {
    @Getter
    private float temp;
    @Getter
    private float pressure;
    @Getter
    private float humidity;
    @Getter
    private float temp_min;
    @Getter
    private float temp_max;

    WeatherMain() {
    }

    public WeatherMain(float temp, float pressure, float humidity, float temp_max, float temp_min) {
        this.temp = temp;
        this.pressure = pressure;
        this.humidity = humidity;
        this.temp_max = temp_max;
        this.temp_min = temp_min;
    }

    @Override
    public String toString() {
        return "WeatherMain [temp=" + temp + ", pressure=" + pressure + ", humidity=" + humidity + ", temp_min="
                + temp_min + ", temp_max=" + temp_max + ", getClass()=" + getClass() + ", hashCode()=" + hashCode()
                + ", toString()=" + super.toString() + "]";
    }
}

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