1 回答

TA貢獻(xiàn)1951條經(jīng)驗(yàn) 獲得超3個(gè)贊
ObjectMapper我編寫(xiě)了一個(gè)示例代碼,通過(guò)使用將響應(yīng) json 字符串轉(zhuǎn)換為 POJO 來(lái) 演示我在評(píng)論中所說(shuō)的內(nèi)容。
首先,創(chuàng)建一個(gè)類(lèi),說(shuō)CoinDeskResponse是存儲(chǔ)轉(zhuǎn)換結(jié)果。
public class CoinDeskResponse {
private TimeInfo time;
private String disclaimer;
private BpiInfo bpi;
//general getters and setters
}
class TimeInfo {
private String updated;
private String updatedISO;
//general getters and setters
}
class BpiInfo {
private String code;
private String symbol;
private String rate;
private String description;
@JsonProperty("rate_float")
private String rateFloat;
//general getters and setters
}
接下來(lái),創(chuàng)建ObjectMapper響應(yīng)并將其轉(zhuǎn)換為CoinDeskResponsePOJO。然后就可以通過(guò)操作該對(duì)象來(lái)獲取所需的數(shù)據(jù)。
String responseStr = "{\"time\":{\"updated\":\"Sep 18, 2013 17:27:00 UTC\",\"updatedISO\":\"2013-09-18T17:27:00+00:00\"},\"disclaimer\":\"This data was produced from the CoinDesk Bitcoin Price Index. Non-USD currency data converted using hourly conversion rate from openexchangerates.org\",\"bpi\":{\"code\":\"USD\",\"symbol\":\"$\",\"rate\":\"126.5235\",\"description\":\"United States Dollar\",\"rate_float\":126.5235}}";
ObjectMapper mapper = new ObjectMapper();
try {
CoinDeskResponse coinDeskResponse = mapper.readValue(responseStr, CoinDeskResponse.class);
System.out.println(coinDeskResponse.getTime().getUpdated());
System.out.println(coinDeskResponse.getBpi().getDescription());
System.out.println(coinDeskResponse.getBpi().getRateFloat());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
控制臺(tái)輸出:
數(shù)據(jù)在 UTC 時(shí)間/日期獲取:2013 年 9 月 18 日 17:27:00 UTC
描述:美元
浮動(dòng)匯率:126.5235
添加回答
舉報(bào)