2016-11-23 47 views
1

我用轉換Json的使用Exchange中的Java/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的,所以我想知道我必須做出一個包含所有這些對象的一類setters/getters(coord字段,id,描述,天氣,名字等等),還是我可以像coord對象和天氣對象一樣製作一個對象,並且只映射那些字段?

感謝您的任何建議。

編輯:

也許這將有事可做與@JsonIgnoreProperties標籤的ignoreUnknown =真正的屬性?

+0

取決於你以後想用它做什麼。如果你只關心迴應的部分內容,爲什麼還要留意呢?如果你需要它們,你可以將JSON映射到一個類,或者只是保留JSON並直接訪問這些字段。爲了便於閱讀,我將JSON轉換爲一個類,但是。 – Robert

+0

我不需要它們。但是我使用openweather.com api,我不能(或者我能以某種方式?)編輯響應,它只是在您進入城市時返回所有這些。我真正需要的是一些領域(如天氣「:[{」id「:741,」main「:」霧「,」描述「:」霧「}),它只是一個簡單的項目我我只是沒有想要與所有這些領域做一個對象 – Smithers

回答

0

我想你只需要兩個類來設置它們的getter和setter類。你的「天氣」變量就是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 
+0

是的,但它似乎只是在那裏太多無用的東西。風有一個速度,一個方向,「主」有一個溫度,壓力,溼度, min temp,max temp,theres a set for clouds,sunrise,sunset,stuff我不需要 – Smithers

+0

你不得不添加你的可用變量到你的班級,不是所有的都是強制性的 –

+0

謝謝你,我做了什麼,我想我知道了,變量名必須和json中的字段名相同嗎?就像我剛剛創建了一個帶有'base'字符串字段的對象,並且它正確設置爲'stations'。 – Smithers

0

如果你想所有的變量映射只是做一個單一的模型類,並映射您的回覆,這樣

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();