我的 JSON 具有以下结构:
{"name": [9000, {Inst1}, ..., {Instn}]}
其中9000
是任意整数,Insti
是某个类的序列化实例。
我正在使用类似的方法将所有 Inst
放入列表中:
Type listType = new TypeToken<ArrayList<Song>>(){}.getType();
并尝试通过编写如下内容来排除第一个 int:
public class ExcludeTotalFound implements ExclusionStrategy {
private final Class<?> typeToSkip;
public ExcludeTotalFound(Class<?> typeToSkip) {
this.typeToSkip = typeToSkip;
}
public boolean shouldSkipClass(Class<?> clas_s) {
return clas_s == typeToSkip;
}
public boolean shouldSkipField(FieldAttributes fieldAttributes) {
return typeToSkip.equals(fieldAttributes.getDeclaredClass());
}
}
最后,我正在做
gson = new GsonBuilder().addDeserializationExclusionStrategy(new ExcludeTotalFound(int.class)).serializeNulls().create();
然后:
collection = gson.fromJson(rBody, listType);
其中 rBody 是所有原始数组,即 {"name": [9000, {Inst1}, ..., {Instn}]
但我得到的只是
com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was NUMBER`
有什么问题吗?
添加: 只要我知道 JSON 的长度永远不会超过 ~500,并且结构始终保持不变,那么使用以下解决方法是否足够好?
Iterator<JsonElement> it = rBody.iterator();
it.next();
while (it.hasNext()) {
collection.add(gson.fromJson(it.next(), Song.class));
}
最佳答案
这看起来与我在这里回答的非常相似 --> Gson custom deserialization 。这有帮助吗?这不是通过排除,而是通过自定义反序列化。
关于java - gson中的排除策略,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16286411/