如何使用Gson反序列化:
public class PageJson {
private final String page;
private final Object results;
public PageJson(String page, Object results) {
this.page = page;
this.results = results;
}
public String getPage() {
return page;
}
public Object getResults() {
return results;
}
}
其中results
是一个任意对象,我可以在获得page
值后识别该类型。
答案 0 :(得分:2)
您可以实施JsonDeserializer
并在Gson
注册:
public class PageJsonDeserializer implements JsonDeserializer<PageJson> {
@Override
public PageJson deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
final JsonObject pageJsonObj = json.getAsJsonObject();
String page = pageJsonObj.get("page").getAsString();
JsonObject results = pageJsonObj.get("results").getAsJsonObject();
//TODO: Decide here according to page which object to construct for results
//and then call the constructor of PageJson
//return constructed PageJson instance
}
}
您需要将类型适配器注册到Gson
。
Gson gson = new GsonBuilder().registerTypeAdapter(PageJson.class, new PageJsonDeserializer()).create();