1 回答

TA貢獻1951條經驗 獲得超3個贊
ObjectMapper我編寫了一個示例代碼,通過使用將響應 json 字符串轉換為 POJO 來 演示我在評論中所說的內容。
首先,創建一個類,說CoinDeskResponse是存儲轉換結果。
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
}
接下來,創建ObjectMapper響應并將其轉換為CoinDeskResponsePOJO。然后就可以通過操作該對象來獲取所需的數據。
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();
}
控制臺輸出:
數據在 UTC 時間/日期獲?。?013 年 9 月 18 日 17:27:00 UTC
描述:美元
浮動匯率:126.5235
添加回答
舉報