我尝试从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 + '\'' +
'}';
}
}
当我尝试获取这些值时,我总是为空
2018-01-12 14:00:14.829 INFO 18017 --- [ main] com.example.demo.BitbayApplication : BTC_ETH{BTC_ETH=null}
为什么会这样?我可以很容易地阅读更简单的JSON,但这个问题有问题。
答案 0 :(得分:2)
BTC_Poloniex类中定义的变量
private BTC_ETH BTC_ETH;
应该是
private BTC_ETH BTC_BCN;
因为json变量是
BTC_BCN
这应该与json CLASS中的变量名相同。
答案 1 :(得分:1)
简单的解决方案是使用地图。 样品如下。
使用此代码,您可以访问json中的每个字段:)
我希望我的解决方案对您来说足够好:)。
@Service
public class RestTemplateService {
@Autowired
RestTemplate restTemplate;
public void getInfoFromPoloniex() {
HashMap<String,Map> answer = restTemplate.getForObject("https://poloniex.com/public?command=returnTicker",
new HashMap<>().getClass());
answer.values().forEach(a -> System.out.println(a.toString()));
System.out.println(answer.get("BTC_GAME").getClass().toString());
answer.get("BTC_GAME").keySet().stream().forEach(k -> System.out.println(k.toString()));
}
}