@The_XXI

Почему присходит ошибка при конвертации json в Java объект (библиотека gson)?

Мне надо преобразовать json в Java объект. При попытке извлечь temp из main появляется ошибка.
Json:
60217b7941122480798631.png
{
    "coord": {
        "lon": 30.2642,
        "lat": 59.8944
    },
    "weather": [
        {
            "id": 800,
            "main": "Clear",
            "description": "clear sky",
            "icon": "01n"
        }
    ],
    "base": "stations",
    "main": {
        "temp": 257.74,
        "feels_like": 253.56,
        "temp_min": 256.15,
        "temp_max": 259.82,
        "pressure": 1022,
        "humidity": 85
    },
    "visibility": 10000,
    "wind": {
        "speed": 1,
        "deg": 230
    },
    "clouds": {
        "all": 0
    },
    "dt": 1612803730,
    "sys": {
        "type": 1,
        "id": 8926,
        "country": "RU",
        "sunrise": 1612763713,
        "sunset": 1612794668
    },
    "timezone": 10800,
    "id": 498817,
    "name": "Saint Petersburg",
    "cod": 200
}


Код Java:
Tree tree = gson.fromJson(line, Tree.class);
System.out.println(tree);

class Tree {
    private String name;
    Weather[] weather;
    <b>@SerializedName("main")
    Temp[] temp;</b>

    @Override
    public String toString() {
        return "Tree{" +
                "name='" + name + '\'' +
                ", weather=" + Arrays.toString(weather) +
                '}';
    }
}

class Weather {
    private String main;

    @Override
    public String toString() {
        return "Weather{" +
                "main='" + main + '\'' +
                '}';
    }
}

class Temp {
    private double temp;
}


Код, который вызывает ошибку:
@SerializedName("main")
Temp[] temp;

ошибка:
Caused by: java.lang.IllegalStateException: Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 143 path $.main
я понимаю, что проблема в том, что "main" встречается и до этого, но не понимаю, как это решить.
  • Вопрос задан
  • 174 просмотра
Решения вопроса 1
azerphoenix
@azerphoenix Куратор тега Java
Java Software Engineer
У вас структура объекта некорректная.
Вот, посмотрите на эту
-----------------------------------com.example.Clouds.java-----------------------------------

package com.example;

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

public class Clouds {

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

}
-----------------------------------com.example.Coord.java-----------------------------------

package com.example;

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

public class Coord {

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

}
-----------------------------------com.example.Example.java-----------------------------------

package com.example;

import java.util.List;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

public class Example {

@SerializedName("coord")
@Expose
public Coord coord;
@SerializedName("weather")
@Expose
public List<Weather> weather = null;
@SerializedName("base")
@Expose
public String base;
@SerializedName("main")
@Expose
public Main main;
@SerializedName("visibility")
@Expose
public int visibility;
@SerializedName("wind")
@Expose
public Wind wind;
@SerializedName("clouds")
@Expose
public Clouds clouds;
@SerializedName("dt")
@Expose
public int dt;
@SerializedName("sys")
@Expose
public Sys sys;
@SerializedName("timezone")
@Expose
public int timezone;
@SerializedName("id")
@Expose
public int id;
@SerializedName("name")
@Expose
public String name;
@SerializedName("cod")
@Expose
public int cod;

}
-----------------------------------com.example.Main.java-----------------------------------

package com.example;

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

public class Main {

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

}
-----------------------------------com.example.Sys.java-----------------------------------

package com.example;

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

public class Sys {

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

}
-----------------------------------com.example.Weather.java-----------------------------------

package com.example;

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

public class Weather {

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

}
-----------------------------------com.example.Wind.java-----------------------------------

package com.example;

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

public class Wind {

@SerializedName("speed")
@Expose
public int speed;
@SerializedName("deg")
@Expose
public int deg;

}

Сгенерировано из - www.jsonschema2pojo.org
Ответ написан
Комментировать
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы
Bell Integrator Ульяновск
До 400 000 ₽
Bell Integrator Хабаровск
До 400 000 ₽
Bell Integrator Ижевск
До 400 000 ₽
26 апр. 2024, в 10:21
1200 руб./в час
26 апр. 2024, в 10:10
1000 руб./за проект