GSON - 基于Field的值排除对象

时间:2012-08-01 13:02:52

标签: gson

我有一些JSON,其中包含一个名为“type”的密钥。此密钥的值为includeexclude。我想配置Gson不反序列化Json,并在键值为exclude时创建一个对象。

我意识到我可以编写自定义反序列化器,检查是否合适,然后创建对象。但是,我不确定是否有其他方式使用某种类型的排除策略。

我概述的例子过于简化了。我真正的JSON包含更多字段。

// Deserialize me
{     
   "type" : "include"
}

// Skip over me, and do not deserialize
{
   "type" : "exclude"
}

2 个答案:

答案 0 :(得分:0)

我不认为ExclusionStrategy可以在这里提供帮助。它适用于类而不是实例,并且在实例处理时,只有其评估结果存在(如果您想查看代码,请参阅ReflectiveTypeAdapterFactory.BoundField)。

答案 1 :(得分:0)

这可能对你有帮助......

Gson gson = new Gson();
JsonObject jsonObj = gson.fromJson (jsonStr, JsonElement.class).getAsJsonObject();

// Just read the required field
if(jsonObj.get("type").getAsString().equals("include")) {
    // Continue parsing/deserializing other details
} else {
    // Skip
}

您可以参考this了解Gson API文档