gpt4 book ai didi

java - 如果反序列化出现错误,是否有一种简单的方法可以让 Gson 跳过一个字段?

转载 作者:行者123 更新时间:2023-12-03 23:09:25 25 4
gpt4 key购买 nike

我正在尝试使用 Gson (Java) 反序列化一些数据,而我从中提取数据的 API 有时会在字段中包含错误类型的数据。 IE。如果我期待 String 的数组类型,它可能会遇到 Boolean .

现在我意识到这些是我目前的选择:

  • 始终忽略反序列化中的字段
  • 创建自定义TypeAdapter进行反序列化并捕获错误并执行某些操作(例如将字段设置为 null )

  • 但是我问是否有另一种方法可以轻松实现,所以如果解析某个字段时出现异常,Gson 将忽略该字段。类似于该字段上的注释,如 @Skippable或者可能是使用 GsonBuilder 时的设置创建 Gson目的?

    有没有人熟悉这样的事情?

    最佳答案

    正确处理JSON 中所有可能出现的错误并非易事。以及有效负载与 POJO 之间的不匹配模型。但是我们可以尝试实现com.google.gson.TypeAdapterFactory接口(interface)和包装所有默认TypeAdaptertry-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
    }

    也可以看看:
  • Same object referenced in two classes, duplicated instance after decode
  • 关于java - 如果反序列化出现错误,是否有一种简单的方法可以让 Gson 跳过一个字段?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59655279/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com