gpt4 book ai didi

java - Gson - 获取通用 SerializedName

转载 作者:行者123 更新时间:2023-12-02 02:30:33 33 4
gpt4 key购买 nike

public class MyClass{
@SerializedName("hello")
private String hello;

@SerializedName("world")
private String world

@SerializedName("dynamic")
private String dynamic;
}

我希望能够将所有动态*名称解析为变量dynamic。示例:

{"hello":"hello", "world":"world", "dynamic123":"qwerty"}

{"hello":"hello", "world":"world", "dynamic345":"asdfgh"}

{"hello":"hello", "world":"world", "dynamic567":"zxcvbn"}

如何实现这一目标?

最佳答案

为您的 MyClass 创建自定义 Gson 反序列化器

public class MyClassDeSerializer implements JsonDeserializer<MyClass> {
@Override
public MyClass deserialize(JsonElement jsonElement, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
MyClass myClass = new MyClass();

for (Map.Entry<String, JsonElement> property : jsonElement.getAsJsonObject().entrySet()) {
if (property.getKey().contains("dynamic")) {
myClass.setDynamic(property.getValue().getAsString());
}
else if (property.equals("hello")) {
myClass.setHello(property.getValue().getAsString());
}
else if (property.getKey().equals("world")) {
myClass.setWorld(property.getValue().getAsString());
}
}
return myClass;
}
}

并通过注册这个类来创建Gson

Gson gson = new GsonBuilder().registerTypeAdapter(MyClass.class , new MyClassDeSerializer()).create();

反序列化

MyClass result = gson.fromJson(json, MyClass.class);

关于java - Gson - 获取通用 SerializedName,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47197921/

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