gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 08:06:17 26 4
gpt4 key购买 nike

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

例如,有一个 json

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

一个类就是

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 的 TypeAdapterFactory,但它使用父类字段并从父 ReflectiveTypeAdapterFactory 中排除 BoundField,而不是确定如何做到这一点,看起来相当复杂。

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. 将已知字段解析到类实例中(未知字段将被忽略)
  2. 将 json 字符串转为 map
  3. 从该 map 中删除已知字段
  4. 将剩余的 map 分配给类(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;

关于java - 在 Google-Gson 中为使用 ReflectiveTypeAdapterFactory 解析的对象创建未定义字段 Map,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31049531/

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