gpt4 book ai didi

java - Gson - 任意对象

转载 作者:塔克拉玛干 更新时间:2023-11-02 19:23:56 25 4
gpt4 key购买 nike

如何用 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 值后我可以识别该类型。

最佳答案

可以实现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();

关于java - Gson - 任意对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24924955/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com