gpt4 book ai didi

java - 如何实现与@JsonUnwrap 等效的 Gson

转载 作者:搜寻专家 更新时间:2023-11-01 02:58:46 25 4
gpt4 key购买 nike

我知道 Gson 没有类似的功能,但是有没有办法像 @JsonUnwrap 那样添加对展开 Json 字段的支持?

目标是允许这样的结构:

public class Person { 
public int age;
public Name name;
}

public class Name {
public String first;
public String last;
}

被(反)序列化为:

{
"age" : 18,
"first" : "Joey",
"last" : "Sixpack"
}

代替:

{
"age" : 18,
"name" : {
"first" : "Joey",
"last" : "Sixpack"
}
}

我知道它可能会变得相当复杂,所以我不是在寻找完整的解决方案,只是寻找一些高级指南(如果可行的话)。

最佳答案

我粗略地实现了一个支持此功能的解串器。它是完全通用的(与类型无关),但也很昂贵且脆弱,我不会将它用于任何严肃的事情。我发帖只是为了向其他人展示我的成果,如果他们最终需要做类似的事情。

public class UnwrappingDeserializer implements JsonDeserializer<Object> {

//This Gson needs to be identical to the global one, sans this deserializer to prevent infinite recursion
private Gson delegate;

public UnwrappingDeserializer(Gson delegate) {
this.delegate = delegate;
}

@Override
public Object deserialize(JsonElement json, Type type, JsonDeserializationContext context) throws JsonParseException {
Object def = delegate.fromJson(json, type); //Gson doesn't care about unknown fields
Class raw = GenericTypeReflector.erase(type);
Set<Field> unwrappedFields = ClassUtils.getAnnotatedFields(raw, GsonUnwrap.class);
for (Field field : unwrappedFields) {
AnnotatedType fieldType = GenericTypeReflector.getExactFieldType(field, type);
field.setAccessible(true);
try {
Object fieldValue = deserialize(json, fieldType.getType(), context);
field.set(def, fieldValue);
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
}
}

return def;
}
}

然后可以通过 new GsonBuilder().registerTypeHierarchyAdapter(Object.class, new UnwrappingDeserializer(new Gson())).create() 或通过 为特定类型注册全局registerTypeAdapter.

注意事项:

  • 真正的实现应该递归检查整个类结构是否存在 GsonUnwrap,将结果缓存在并发映射中,并且仅在需要时才执行此过程。否则它应该立即返回 def
  • 它还应该缓存发现的注释字段以避免每次都扫描层次结构
  • GenericTypeReflector 来自 GeAnTyRef
  • ClassUtils#getAnnotatedFields 是我自己的实现,但它没有做任何特别的事情 - 它只是为类层次结构递归地收集声明的字段(通过 Class#getDeclaredFields)
  • GsonUnwrap只是一个简单的自定义注解

我想序列化也可以做类似的事情。示例链接自 Derlin's answer可以作为起点。

关于java - 如何实现与@JsonUnwrap 等效的 Gson,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43294694/

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