1

Хочу получить данные о погоде отсюда. Но мне нужна не вся инфа, только часть (температура, описание, влажность и местоположение). Пробил ссылку через http://www.jsonschema2pojo.org и получил множество классов. Какой же использовать именно для моих задач? Заранее спасибо

Вот список всех классов

package com.example;

import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

public class Clouds {

    @SerializedName("all")
    @Expose
    private int all;

    public int getAll() {
        return all;
    }

    public void setAll(int all) {
        this.all = all;
    }

}

package com.example;

import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

public class Coord {

    @SerializedName("lon")
    @Expose
    private double lon;
    @SerializedName("lat")
    @Expose
    private double lat;

    public double getLon() {
        return lon;
    }

    public void setLon(double lon) {
        this.lon = lon;
    }

    public double getLat() {
        return lat;
    }

    public void setLat(double lat) {
        this.lat = lat;
    }

}

import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

public class Coord {

    @SerializedName("lon")
    @Expose
    private double lon;
    @SerializedName("lat")
    @Expose
    private double lat;

    public double getLon() {
        return lon;
    }

    public void setLon(double lon) {
        this.lon = lon;
    }

    public double getLat() {
        return lat;
    }

    public void setLat(double lat) {
        this.lat = lat;
    }

}
package com.example;

import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

public class Main {

    @SerializedName("temp")
    @Expose
    private double temp;
    @SerializedName("feels_like")
    @Expose
    private double feelsLike;
    @SerializedName("temp_min")
    @Expose
    private double tempMin;
    @SerializedName("temp_max")
    @Expose
    private int tempMax;
    @SerializedName("pressure")
    @Expose
    private int pressure;
    @SerializedName("humidity")
    @Expose
    private int humidity;

    public double getTemp() {
        return temp;
    }

    public void setTemp(double temp) {
        this.temp = temp;
    }

    public double getFeelsLike() {
        return feelsLike;
    }

    public void setFeelsLike(double feelsLike) {
        this.feelsLike = feelsLike;
    }

    public double getTempMin() {
        return tempMin;
    }

    public void setTempMin(double tempMin) {
        this.tempMin = tempMin;
    }

    public int getTempMax() {
        return tempMax;
    }

    public void setTempMax(int tempMax) {
        this.tempMax = tempMax;
    }

    public int getPressure() {
        return pressure;
    }

    public void setPressure(int pressure) {
        this.pressure = pressure;
    }

    public int getHumidity() {
        return humidity;
    }

    public void setHumidity(int humidity) {
        this.humidity = humidity;
    }

}```

```package com.example;

import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

public class Sys {

    @SerializedName("type")
    @Expose
    private int type;
    @SerializedName("id")
    @Expose
    private int id;
    @SerializedName("country")
    @Expose
    private String country;
    @SerializedName("sunrise")
    @Expose
    private int sunrise;
    @SerializedName("sunset")
    @Expose
    private int sunset;

    public int getType() {
        return type;
    }

    public void setType(int type) {
        this.type = type;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getCountry() {
        return country;
    }

    public void setCountry(String country) {
        this.country = country;
    }

    public int getSunrise() {
        return sunrise;
    }

    public void setSunrise(int sunrise) {
        this.sunrise = sunrise;
    }

    public int getSunset() {
        return sunset;
    }

    public void setSunset(int sunset) {
        this.sunset = sunset;
    }

}

import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

public class Weather {

    @SerializedName("id")
    @Expose
    private int id;
    @SerializedName("main")
    @Expose
    private String main;
    @SerializedName("description")
    @Expose
    private String description;
    @SerializedName("icon")
    @Expose
    private String icon;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getMain() {
        return main;
    }

    public void setMain(String main) {
        this.main = main;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public String getIcon() {
        return icon;
    }

    public void setIcon(String icon) {
        this.icon = icon;
    }

}

import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

public class Wind {

    @SerializedName("speed")
    @Expose
    private int speed;

    public int getSpeed() {
        return speed;
    }

    public void setSpeed(int speed) {
        this.speed = speed;
    }

}

Код NetworkRequest

public class NetworkRequest {
    private static NetworkRequest request;
    private static final String BASE_URL = "https://api.openweathermap.org/";
    private Retrofit retrofit;

    NetworkRequest() {
        retrofit = new Retrofit.Builder()
                .baseUrl(BASE_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .build();
    }

    public static NetworkRequest getRequest(){
        if(request == null){
            request = new NetworkRequest();
        }
        return request;
    }

    public WeatherAPI getWeatherApi(){
        return  retrofit.create(WeatherAPI.class);
    }
}

Интерфейс

public interface WeatherAPI {
    @GET ("data/2.5/weather?id=532096")
    Call<Weather> getWeather();
}

MainActivity

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        final TextView tvLocation = findViewById(R.id.tv_location);
        final TextView tvTemperature = findViewById(R.id.tv_temperature);
        final TextView tvDescription = findViewById(R.id.tv_description);
        final TextView tvHumidity = findViewById(R.id.tv_humidity);


        NetworkRequest networkRequest = new NetworkRequest();
        networkRequest.getRequest()
                .getWeatherApi()
                .getWeather()
                .enqueue(new Callback<Weather>() {
                    @Override
                    public void onResponse(Call<Weather> call, Response<Weather> response) {
                        Weather weather = response.body();

                        tvLocation.append(weather.getLocale());
                        tvDescription.append(weather.getDescription());
                        tvTemperature.append(weather.getTemperature());
                        tvHumidity.append(weather.getHumidity());
                    }

                    @Override
                    public void onFailure(Call<Weather> call, Throwable t) {
                        Toast.makeText(MainActivity.this, "Не удалось", Toast.LENGTH_LONG).show();
                    }
                });

    }
}

Класс Weather

public class Weather {
@SerializedName("name")
@Expose
private String locale = "Город";

@SerializedName("temp")
@Expose
private String temperature = "Температура";

@SerializedName("description")
@Expose
private String description = "Статус";

@SerializedName("humidity")
@Expose
private String humidity = "Влажность";

public String getLocale() {
    return locale;
}
public void setLocale(String locale) {
    this.locale = locale;
}

public String getTemperature() {
    return temperature;
}
public void setTemperature(String temperature) {
    this.temperature = temperature;
}

public String getDescription() {
    return description;
}
public void setDescription(String description) {
    this.description = description;
}

public String getHumidity() {
    return humidity;
}
public void setHumidity(String humidity) {
    this.humidity = humidity;
}
}

1 ответ 1

1

Убираешь ненужное и оставляешь то, что нужно тебе

data class WeatherData(
    @SerializedName("coord")
    val coord: Coord, //Местоположение
    @SerializedName("weather")
    val weather: List<Weather>
)

data class Coord(
    @SerializedName("lat")
    val lat: Float,
    @SerializedName("lon")
    val lon: Float
)

data class Main(
    @SerializedName("humidity")
    val humidity: Int, //Влажность
    @SerializedName("temp")
    val temp: Float //Температура
)

data class Weather(
    @SerializedName("description")
    val description: String //Описание
)

UPD Тоже самое на Java

class WeatherData {
    @SerializedName("coord")
    Coord coord; //Местоположение
    @SerializedName("weather")
    List<Weather> weather;
}

class Coord {
    @SerializedName("lat")
    Float lat;
    @SerializedName("lon")
    Float lon;
}

class Main {
    @SerializedName("humidity")
    int humidity; //Влажность
    @SerializedName("temp")
    Float temp; //Температура
}

class Weather {
    @SerializedName("description")
    String description; //Описание
}
17
  • то есть мне нужно создать 4 интерфейса и по очереди получать данные? 13 мая 2020 в 14:19
  • Какие интерфейсы? Это pojo на котлине
    – Circassian
    13 мая 2020 в 14:20
  • мне нужно получить эти данные в приложении, используя Retrofit 13 мая 2020 в 14:23
  • 1
    Вопрос стоял так: Какие классы использовать для моих задач? Теперь мы пришли к тому, что не умеешь пользоваться Retrofit'ом?
    – Circassian
    13 мая 2020 в 14:25
  • судя по всему - да. Использую его второй раз. При первом запросе данных было на порядок меньше. Поэтому вновь спрашиваю. Мне нужно создать 4 отдельных интерфейса или все это можно объединить в 1? 13 мая 2020 в 14:29

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge you have read our privacy policy.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.