gpt4 book ai didi

java - 对象中一个变量的 Gson 自定义解串器

转载 作者:IT老高 更新时间:2023-10-28 12:50:48 25 4
gpt4 key购买 nike

我的问题示例:

我们有一个 Apple 的对象类型。苹果有一些成员变量:

String appleName; // The apples name
String appleBrand; // The apples brand
List<Seed> seeds; // A list of seeds the apple has

种子对象如下所示。

String seedName; // The seeds name
long seedSize; // The size of the seed

现在当我得到一个苹果对象时,一个苹果可能有多个种子,或者它可能有一个种子,或者可能没有种子!

带有一个种子的 JSON 苹果示例:

{
"apple" : {
"apple_name" : "Jimmy",
"apple_brand" : "Awesome Brand" ,
"seeds" : {"seed_name":"Loopy" , "seed_size":"14" }
}
}

带有两个种子的 JSON 苹果示例:

{
"apple" : {
"apple_name" : "Jimmy" ,
"apple_brand" : "Awesome Brand" ,
"seeds" : [
{
"seed_name" : "Loopy",
"seed_size" : "14"
},
{
"seed_name" : "Quake",
"seed_size" : "26"
}
]}
}

现在这里的问题是第一个示例是用于种子的 JSONObject,第二个示例是用于种子的 JSONArray。现在我知道它的 JSON 不一致,修复它的最简单方法是修复 JSON 本身,但不幸的是我从其他人那里得到了 JSON,所以我无法修复它。解决此问题的最简单方法是什么?

最佳答案

您需要为 Apple 类型注册一个自定义类型适配器。在类型适配器中,您将添加逻辑以确定是否给您一个数组或单个对象。使用该信息,您可以创建 Apple 对象。

除了以下代码,修改您的 Apple 模型对象,以便不会自动解析 seeds 字段。将变量声明更改为:

private List<Seed> seeds_funkyName;

代码如下:

GsonBuilder b = new GsonBuilder();
b.registerTypeAdapter(Apple.class, new JsonDeserializer<Apple>() {
@Override
public Apple deserialize(JsonElement arg0, Type arg1,
JsonDeserializationContext arg2) throws JsonParseException {
JsonObject appleObj = arg0.getAsJsonObject();
Gson g = new Gson();
// Construct an apple (this shouldn't try to parse the seeds stuff
Apple a = g.fromJson(arg0, Apple.class);
List<Seed> seeds = null;
// Check to see if we were given a list or a single seed
if (appleObj.get("seeds").isJsonArray()) {
// if it's a list, just parse that from the JSON
seeds = g.fromJson(appleObj.get("seeds"),
new TypeToken<List<Seed>>() {
}.getType());
} else {
// otherwise, parse the single seed,
// and add it to the list
Seed single = g.fromJson(appleObj.get("seeds"), Seed.class);
seeds = new ArrayList<Seed>();
seeds.add(single);
}
// set the correct seed list
a.setSeeds(seeds);
return a;
}
});

有关更多信息,请参阅 Gson guide .

关于java - 对象中一个变量的 Gson 自定义解串器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6014674/

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