我在映射json时遇到这样的问题:
{
"data": {
"id": 2,
"name": "Litecoin",
"symbol": "LTC",
"website_slug": "litecoin",
"rank": 7,
"circulating_supply": 57656657.0,
"total_supply": 57656657.0,
"max_supply": 84000000.0,
"quotes": {
"USD": {
"price": 77.9238663379,
"volume_24h": 334368162.90084,
"market_cap": 4492829637.0,
"percent_change_1h": -0.05,
"percent_change_24h": -1.5,
"percent_change_7d": -9.95
},
"EUR": {
"price": 66.6913747769,
"volume_24h": 286169995.3231736,
"market_cap": 3845201724.0,
"percent_change_1h": -0.05,
"percent_change_24h": -1.5,
"percent_change_7d": -9.95
}
},
"last_updated": 1533123370
},
"metadata": {
"timestamp": 1533122956,
"error": null
}
}
如您所见;引用对象中的对象名称是动态的,我不知道引用对象中将有多少个对象。我认为服务器应将其放入数组中,但我无法控制API /
其他所有内容都正确映射,只有引号对象的内容为空
我可以用gson和Retrofit映射吗?
我尝试过的:
public class Quotes {
//region variables
private Map<String, Fiat> fiatMap;
//endregion
//region getters
public Map<String, Fiat> getFiatMap() {
return fiatMap;
}
//endregion
//region setters
public void setFiatMap(Map<String, Fiat> fiatMap) {
this.fiatMap = fiatMap;
}
//endregion
}
我的服务是什么样的:
Retrofit.Builder builder = new Retrofit.Builder()
.baseUrl(Constants.BASE_URL)
.client(client)
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.addConverterFactory(GsonConverterFactory.create());
Retrofit retrofit = builder.build();
client = retrofit.create(MyCLient.class)
答案 0 :(得分:0)
您可以为该类编写自定义反序列化器。
gson = new GsonBuilder()
.registerTypeAdapter(Quotes.class, new MyCustomDeserializer())
.create();
public class MyCustomDeserializer implements JsonDeserializer<Quotes> {
@Override
public Quotes deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
// Your custom deserilizer here
}
}
然后,您必须将gson
设置为改造生成器中的转换器