在 Google-Gson 中为使用 ReflectiveTypeAdapterFactory 解析的对象创建一个未定义的字段 Map

Create an undefined field Map in Google-Gson for object parsed with ReflectiveTypeAdapterFactory

我想创建一个 Map 字段,其中包含要解析的 class 中未定义的所有其他字段。

例如,有一个 json

{
    "first": "value",
    "second": "value",
    "unknown": "value",
    "undefined": "value"
}

而 class 将是

public class DaClass {

    @SerializedName("first")
    private String mFirst;

    @SerializedName("second")
    private String mSecond;

    @UndefinedMap // This annotation does not exist. I've put it here for an example,
                  // to indicate this is not a regular Map for key "mUndefined", but
                  // rather a map to put unparsed fields to.
    private Map<String, ?> mUndefined;
}

mUndefined 内容所在的位置

key="unknown" value="value"
key="undefined" value="value"

一个想法是创建自定义 Map 类型并创建类似于 MapTypeAdapterFactory 但使用父 class 字段并从父 ReflectiveTypeAdapterFactory 中排除 BoundField 的 TypeAdapterFactory,而不是确定如何执行此操作,看起来很复杂。

public class DaClass {

    @SerializedName("first")
    private String mFirst;

    @SerializedName("second")
    private String mSecond;

    private UndefinedMap<String, ?> mUndefined;
}

gsonBuilder.registerTypeAdapter(UndefinedMap.class, new UndefinedMapTypeAdapterFactory());

但真正的问题是,是否已经有类似的支持?

我已经解决了这个问题(使用 Gson 2.8.2):

  1. 将已知字段解析为class实例(忽略未知字段)
  2. 将 json 字符串转换为映射
  3. 从地图中删除已知字段
  4. 将剩余的地图分配给 class 成员

示例代码:

    DaClass daClass = new Gson().fromJson(jsonString.toString(), DaClass.class);

    Type type = new TypeToken<Map<String, Object>>() {}.getType();
    Map<String, Object> mapOfUndefined = new Gson().fromJson(jsonString.toString(), type);

    mapOfUndefined.remove("first");
    mapOfUndefined.remove("second");

    daClass.mUndefined = mapOfUndefined;