我试图在retrofit / gson中解析json响应,特别是this json
{
"Coincheck":{
"BTC":[
"JPY"
]
},
"QuadrigaCX":{
"ETH":[
"CAD",
"BTC"
],
"BTC":[
"USD",
"CAD"
]
}
// ... more data
}
我尝试使用Map<字符串,地图<字符串,列表<串GT;>
public class ExchangeResp
{
Map<String, Map<String, List<String>>> exchanges;
public Map<String, Map<String, List<String>>> getExchanges()
{
return exchanges;
}
}
但我总是将response.body()视为null。我是否需要创建实现JsonDeserializer的自定义json desrializer并传递给gson builder?
答案 0 :(得分:0)
将您的回复类用作
import com.google.gson.annotations.SerializedName;
import java.util.List;
public class Reposne {
@SerializedName("Coincheck")
private Coincheck coincheck;
@SerializedName("QuadrigaCX")
private QuadrigaCX quadrigaCX;
public Coincheck getCoincheck() {
return coincheck;
}
public void setCoincheck(Coincheck coincheck) {
this.coincheck = coincheck;
}
public QuadrigaCX getQuadrigaCX() {
return quadrigaCX;
}
public void setQuadrigaCX(QuadrigaCX quadrigaCX) {
this.quadrigaCX = quadrigaCX;
}
class Coincheck {
@SerializedName("BTC")
private List<String> btc;
public List<String> getBtc() {
return btc;
}
public void setBtc(List<String> btc) {
this.btc = btc;
}
}
class QuadrigaCX {
@SerializedName("ETH")
private List<String> eth;
@SerializedName("BTC")
private List<String> btc;
public List<String> getEth() {
return eth;
}
public void setEth(List<String> eth) {
this.eth = eth;
}
public List<String> getBtc() {
return btc;
}
public void setBtc(List<String> btc) {
this.btc = btc;
}
}
}
答案 1 :(得分:0)
添加以下三个模型类
public class Item {
@SerializedName("Coincheck")
@Expose
private Coincheck coincheck;
@SerializedName("QuadrigaCX")
@Expose
private QuadrigaCX quadrigaCX;
public Coincheck getCoincheck() {
return coincheck;
}
public void setCoincheck(Coincheck coincheck) {
this.coincheck = coincheck;
}
public QuadrigaCX getQuadrigaCX() {
return quadrigaCX;
}
public void setQuadrigaCX(QuadrigaCX quadrigaCX) {
this.quadrigaCX = quadrigaCX;
}
}
Coincheck.java
public class Coincheck {
@SerializedName("BTC")
@Expose
private List<String> bTC = null;
public List<String> getBTC() {
return bTC;
}
public void setBTC(List<String> bTC) {
this.bTC = bTC;
}
}
QuadrigaCX
public class QuadrigaCX {
@SerializedName("ETH")
@Expose
private List<String> eTH = null;
@SerializedName("BTC")
@Expose
private List<String> bTC = null;
public List<String> getETH() {
return eTH;
}
public void setETH(List<String> eTH) {
this.eTH = eTH;
}
public List<String> getBTC() {
return bTC;
}
public void setBTC(List<String> bTC) {
this.bTC = bTC;
}
}
使用retrfit进行网络通话应该像
call1.enqueue(new Callback<Item>() {
@Override
public void onResponse(Call<Item> call, Response<Item> response) {
}
@Override
public void onFailure(Call<Item> call, Throwable t) {
}
});