Tell me how to properly use GSON, or where you can find information about its use?

I want to take the WeatherOpenApi data and create a new Weather object, filling its variables name , main , maxtemp received data.

By what actions should the data that I get in the form of json should be distributed among the class variables? As an example, I looked here , but there the number of object variables is equal to the number of arguments in json — and in my case there is a lot of superfluous information — how to weed out the extra?

 public class MainActivity extends AppCompatActivity { public class Weather { String main; String name; double maxtemp; } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); String jsonlink = "{\"coord\":{\"lon\":-0.13,\"lat\":51.51},\"weather\":[{\"id\":310,\"main\":\"Drizzle\",\"description\":\"light intensity drizzle rain\",\"icon\":\"09d\"},{\"id\":500,\"main\":\"Rain\",\"description\":\"light rain\",\"icon\":\"10d\"}],\"base\":\"cmc stations\",\"main\":{\"temp\":280.87,\"pressure\":1007,\"humidity\":87,\"temp_min\":280.15,\"temp_max\":281.75},\"wind\":{\"speed\":4.6,\"deg\":230},\"clouds\":{\"all\":90},\"dt\":1459925764,\"sys\":{\"type\":1,\"id\":5168,\"message\":0.0045,\"country\":\"GB\",\"sunrise\":1459920191,\"sunset\":1459968198},\"id\":2643743,\"name\":\"London\",\"cod\":200}"; GsonBuilder builder = new GsonBuilder(); Gson gson = builder.create(); Weather weather = gson.fromJson(jsonlink, Weather.class); Log.i("Name", weather.name); } } 

I would be grateful for the help!

    1 answer 1

    Just do not declare fields in a class whose data you do not need.

    For example, if such an answer comes

     { "coord": { "lon": 139, "lat": 35 }, "main": { "temp": 289.5, "humidity": 89, "pressure": 1013, "temp_min": 287.04, "temp_max": 292.04 }, "dt": 1369824698, "id": 1851632, "name": "Shuzenji", "cod": 200 } 

    And only the main object, id, name, code are needed from it, then it will be enough to declare classes with the following fields:

     public class Weather { public Main main; public long id; public String name; public int code; } public class Main { public float temp; public int humidity; public int pressure; @SerializedName("temp_min") public float tempMax; @SerializedName("temp_max") public float tempMin; } 

    And then GSON will automatically fill them using the received JSON response.

    When creating model classes, it is necessary to take into account the JSON structure, i.e. if you try to convert the above JSON to the Main class like this:

     Gson gson = new Gson(); Main main = gson.fromJson(json, Main.class); 

    then in this case an exception will be thrown, or an object that is not correctly filled in, if their fields overlap, because the root element in the response structure is the Weather object, and Gson will try to fill its fields.

    • @Denis, thanks! - Anton Volkov