使用Gson反序列化JSON时,有没有办法跳过JSON数组中的空条目?
[
{
text: "adsfsd...",
title: "asdfsd..."
},
null,
{
text: "adsfsd...",
title: "asdfsd..."
}
]
结果列表有3个条目,第二个列表为空。我想配置Gson跳过空值,但我找不到办法。
答案 0 :(得分:4)
您可以通过编写自己的自定义gson JsonDeserializer
来排除空值假设您有模型类
class GetData {
private String title;
private String text;
}
class CustomDeserializer implements JsonDeserializer<List<GetData>> {
@Override
public List<GetData> deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext context) throws JsonParseException {
JsonArray jsonArray = jsonElement.getAsJsonArray();
List<GetData> list=new ArrayList<>(30);
Gson gson = new Gson();
for (JsonElement element : jsonArray) {
// skipping the null here, if not null then parse json element and add in collection
if(!(element instanceof JsonNull))
{
list.add(gson.fromJson(element, GetData.class));
}
}
return list;
}
最后你可以解析它
Gson gson = new GsonBuilder().registerTypeHierarchyAdapter(Collection.class, new CustomDeserializer()).create();
gson.fromJson(builder.toString(), Collection.class);
答案 1 :(得分:0)
默认情况下,只要您不将serializeNulls()
设置为GsonBuilder,就会排除空值。一旦我发现了这个。并为我工作:
class CollectionAdapter implements JsonSerializer<Collection<?>> {
@Override
public JsonElement serialize(Collection<?> src, Type typeOfSrc, JsonSerializationContext context) {
if (src == null || src.isEmpty()) // exclusion is made here
return null;
JsonArray array = new JsonArray();
for (Object child : src) {
JsonElement element = context.serialize(child);
array.add(element);
}
return array;
}
}
然后通过以下代码注册:
Gson gson = new GsonBuilder().registerTypeHierarchyAdapter(Collection.class, new CollectionAdapter()).create();
希望这会有所帮助.. :)