A
A
Anton Volkov2016-04-06 16:04:25
Android
Anton Volkov, 2016-04-06 16:04:25

What is the correct way to use GSON for weather parsing?

Good afternoon!
Can you tell me how to use GSON correctly, or where can I find information about its use?
I want to take the WeatherOpenApi data and create a new Weather object, filling its name, main, maxtemp variables with the received data.
Due to what actions should the data that I receive in the form of json be distributed among the class variables? Developer.alexanderklimov.ru/android/library/gson.php looked as an example , but there the number of object variables is equal to the number of arguments in json - and in my case it turns out a lot of unnecessary information - how to weed out the excess?

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 will be grateful for your help!

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Andrey Myvrenik, 2016-04-06
@gim0

It is enough to create a class and use the @SerializedName annotation in the Weather class to specify what to put where. There is no need to cut something. If Gson does not find where to put the data (there is no similar field name in the Weather class or is not specified using the annotation), then it will not put it anywhere. What exactly is the problem?

T
Tiberal, 2016-04-06
@Tiberal

https://github.com/google/gson/blob/master/UserGuide.md

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question