使用Exchange()将Json转换为Java / Spring中的Object

时间:2016-11-23 02:55:56

标签: java json spring

我正在使用

 ResponseEntity<List<item>> res = restTemplate.exchange(
                "http://localhost:8080/page",
                HttpMethod.GET,
                null,
                new ParameterizedTypeReference<List<item>>() {});

对于我的一个应用程序,但由于我进行了休息服务,它只通过Json返回了2个项目。我的问题是,我正在尝试获取天气和api我正在使用返回:

{"coord":{"lon":-0.13,"lat":51.51},"weather":    [{"id":741,"main":"Fog","description":"fog","icon":"50n"},{"id":701,"main":"Mist","description":"mist","icon":"50n"}],"base":"stations","main":{"temp":278.47,"pressure":1012,"humidity":100,"temp_min":277.15,"temp_max":279.15},"visibility":10000,"wind":{"speed":1},"clouds":{"all":75},"dt":1479864000,"sys":{"type":1,"id":5093,"message":0.0311,"country":"GB","sunrise":1479886350,"sunset":1479916868},"id":2643743,"name":"London","cod":200}

那是很多JSON,所以我想知道我是否必须制作一个包含所有那些具有setter / getters(coord字段,id,描述,天气,名称等等)的对象的类,或者我可以只是像coord对象和天气对象一样创建一个对象,并且只有那些字段映射?

感谢您的任何建议。

编辑:

也许它与@JsonIgnoreProperties标签的ignoreUnknown = true属性有关?

2 个答案:

答案 0 :(得分:0)

我认为你只需要两个类来设置getter和setter类。你的天气&#34;变量只是List,其他是静态变量。我会这样做:

public class Weather {

  private Long id;

  private String name;

  private Long cod;

  private coordLong string;

  private coordLat string;

  priva... baseStations, cloudsAll, windSpeed, mainTemp...

  private List<WeatherList> weatherList;

  ...
  //getters setters

答案 1 :(得分:0)

如果您想要映射所有变量,只需创建一个Model类并映射您的响应,就像这样

public class WeatherData{

private Coordinate coord;
private List<Weather> weather;

//Getters and setters setCoord(),getCoord().setWeather(),getWeather().

public class Coordinate{

    private Double lon;
    private Double lat;
    //Getters and Setters
}

public class Weather{

    private Integer id;
    private String main;
    private String description;
    private String icon;

    //Getters and setters
}

//Remaining fields

}

然后像这样映射你的json

//json is your response in String format
Gson gson = new Gson();
WeatherData weatherData = gson.fromJson(json,WeatherData.class);
//handle exception here

然后得到像这样的任何变量值

lat = weatherData.getCoord().getLat();
相关问题