Gson - 任意对象

时间:2014-07-24 04:08:06

标签: java json gson

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

1 个答案:

答案 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();