使用 Retrofit 2 我使用了一个 API,该 API 返回一个具有以下响应的 JSON 对象:
{
"status": "ok",
"questions": {
"1": "What was your childhood nickname?"
}
}
使用 GSON,我想将其序列化为以下类:
public class SecurityQuestionList {
public String status;
public Map<String, String> questions;
}
我已经用我的 Gson 对象注册了一个 TypeAdapter,但问题总是空的。
.registerTypeAdapter(new TypeToken<Map<String, String>>() {}.getType(), new TypeAdapter<Map<String, String>>() {
@Override
public void write(JsonWriter out, Map<String, String> value) throws IOException {
}
@Override
public Map<String, String> read(JsonReader in) throws IOException {
Map<String, String> map = new HashMap<String, String>();
try {
in.beginArray();
while (in.hasNext()) {
map.put(in.nextString(), in.nextString());
}
in.endArray();
} catch (IOException ex) {
}
return map;
}
})
我做错了什么?
最佳答案
在创建 Retrofit
实例时调用 addConverterFactory(GsonConverterFactory.create())
应该就足够了。
关于android - GSON 映射键值对,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40978159/