我正在尝试使用 Gson (Java) 反序列化一些数据,而我从中提取数据的 API 有时在字段中包含错误类型的数据。 IE。如果我期待一个数组String
类型,它可能会遇到Boolean
.
现在我意识到这些是我当前的选择:
- 始终忽略反序列化中的字段
- 创建自定义
TypeAdapter
进行反序列化并捕获错误并执行某些操作(例如将字段设置为null
)
但是我问是否有另一种方法可以轻松实现,因此如果解析某个字段出现异常,Gson 将忽略该字段。类似于该字段上的注释之类的东西@Skippable
或者可能是使用时的设置GsonBuilder
创建一个Gson
object?
有人熟悉这样的事情吗?
正确处理所有可能出现的错误并不是一件容易的事JSON
以及有效负载和之间的不匹配POJO
模型。但我们可以尝试去实现com.google.gson.TypeAdapterFactory
接口并包装所有默认值TypeAdapter
s in try-catch
并跳过无效数据。示例解决方案可能如下所示:
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.TypeAdapter;
import com.google.gson.TypeAdapterFactory;
import com.google.gson.reflect.TypeToken;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
public class GsonApp {
public static void main(String[] args) throws Exception {
File jsonFile = new File("./resource/test.json").getAbsoluteFile();
Gson gson = new GsonBuilder()
.setLenient()
.registerTypeAdapterFactory(new IgnoreFailureTypeAdapterFactory())
.create();
Entity entries = gson.fromJson(new FileReader(jsonFile), Entity.class);
System.out.println(entries);
}
}
class IgnoreFailureTypeAdapterFactory implements TypeAdapterFactory {
public final <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
final TypeAdapter<T> delegate = gson.getDelegateAdapter(this, type);
return createCustomTypeAdapter(delegate);
}
private <T> TypeAdapter<T> createCustomTypeAdapter(TypeAdapter<T> delegate) {
return new TypeAdapter<T>() {
@Override
public void write(JsonWriter out, T value) throws IOException {
delegate.write(out, value);
}
@Override
public T read(JsonReader in) throws IOException {
try {
return delegate.read(in);
} catch (Exception e) {
in.skipValue();
return null;
}
}
};
}
}
class Entity {
private Integer id;
private String name;
// getters, setters, toString
}
例如,上面的代码打印:
Entity{id=null, name='1'}
对于下面JSON
有效负载:
{
"id": [
{
"a": "A"
}
],
"name": 1
}
也可以看看:
- 两个类中引用相同的对象,解码后实例重复 https://stackoverflow.com/questions/58841054/gson-same-object-referenced-in-two-classes-duplicated-instance-after-decode
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)