对象中一个变量的 Gson 自定义反序列化程序

2022-09-01 09:48:56

我的问题示例:

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

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,所以我无法修复它。解决此问题的最简单方法是什么?


答案 1

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

除以下代码外,请修改 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 指南


答案 2

我遇到了同样的问题。我认为我的解决方案稍微简单一些,更通用:

Gson gson = new GsonBuilder()
        .registerTypeAdapter(List.class, new JsonSerializer<List<?>>() {
            @Override
            public JsonElement serialize(List<?> list, Type t,
                    JsonSerializationContext jsc) {
                if (list.size() == 1) {
                    // Don't put single element lists in a json array
                    return new Gson().toJsonTree(list.get(0));
                } else {
                    return new Gson().toJsonTree(list);
                }
            }
        }).create();

当然,我同意原来的海报,最好的解决方案是改变json。大小为 1 的数组没有错,它将使序列化和反序列化变得更加简单!不幸的是,有时这些变化是你无法控制的。