【发布时间】:2018-01-12 13:04:08
【问题描述】:
我尝试从 JSON 中解析值:
{"BTC_BCN":{"id":7,"last":"0.00000086","lowestAsk":"0.00000086","highestBid":"0.00000085","percentChange":"0.14666666","baseVolume":"368.86654762","quoteVolume":"498378738.00151879","isFrozen":"0","high24hr":"0.00000086","low24hr":"0.00000068"},"BTC_ETH":{"id":8,"last":"0.00003800","lowestAsk":"0.00003815","highestBid":"0.00003800","percentChange":"0.12326337","baseVolume":"34.17037464","quoteVolume":"955538.55551651","isFrozen":"0","high24hr":"0.00003883","low24hr":"0.00003221"}}
我感兴趣的值是"id":8,"last":"0.00003800"。
我有 RestTemplate 的 bean:
@Bean
public RestTemplate restTemplate(RestTemplateBuilder builder) {
return builder.build();
}
每 5 秒通过 API 询问网站的那个
@Bean
public CommandLineRunner run(RestTemplate restTemplate) throws Exception {
return args -> {
while(true)
{
BTC_Poloniex btc_poloniex = restTemplate.getForObject(
"https://poloniex.com/public?command=returnTicker", BTC_Poloniex.class);
log.info(btc_poloniex.toString());
TimeUnit.SECONDS.sleep(5);
}
};
}
和读取值的类:
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
@JsonIgnoreProperties(ignoreUnknown = true)
public class BTC_Poloniex {
private BTC_BCN BTC_BCN;
public BTC_Poloniex() {}
public BTC_BCN getBTC_BCN() {
return BTC_BCN;
}
public void setBTC_BCN(BTC_BCN btc_bcn)
{
this.BTC_BCN = btc_bcn;
}
@Override
public String toString() {
return "BTC_Poloniex{" +
"BTC_BCN=" + BTC_BCN +
'}';
}
}
和类(我认为如果是内部类会更好)
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
@JsonIgnoreProperties(ignoreUnknown = true)
public class BTC_BCN {
private long id;
private long last;
private long lowestAsk;
public BTC_BCN(){}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public long getLast() {
return last;
}
public void setLast(long last) {
this.last = last;
}
public long getLowestAsk() {
return lowestAsk;
}
public void setLowestAsk(long lowestAsk) {
this.lowestAsk = lowestAsk;
}
public String toString()
{
return "BTC_BCN{" +
" id='" + id + '\'' +
" last'= " + last + '\'' +
" lowestAsk'= " + lowestAsk + '\'' +
'}';
}
}
当我尝试获取这些值时,我总是有 null
2018-01-12 14:00:14.829 INFO 18017 --- [ main] com.example.demo.BitbayApplication : BTC_ETH{BTC_ETH=null}
为什么会这样?我可以轻松阅读更简单的 JSON,但对此有问题。
【问题讨论】:
标签: java json spring resttemplate