Gson自定义deseralizer,用于对象中的一个变量

Jac*_*son 29 java json gson

我的例子:

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

String appleName; // The apples name
String appleBrand; // The apples brand
List<Seed> seeds; // A list of seeds the apple has
Run Code Online (Sandbox Code Playgroud)

种子对象如下所示.

String seedName; // The seeds name
long seedSize; // The size of the seed
Run Code Online (Sandbox Code Playgroud)

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

带有一个种子的示例JSON apple:

{
"apple" : {
   "apple_name" : "Jimmy", 
   "apple_brand" : "Awesome Brand" , 
   "seeds" : {"seed_name":"Loopy" , "seed_size":"14" }
  }
}
Run Code Online (Sandbox Code Playgroud)

示例JSON apple有两个种子:

{
"apple" : {
   "apple_name" : "Jimmy" , 
   "apple_brand" : "Awesome Brand" , 
   "seeds" : [ 
      { 
         "seed_name" : "Loopy",
         "seed_size" : "14"
      },
      {
         "seed_name" : "Quake",
         "seed_size" : "26"
      } 
  ]}
}
Run Code Online (Sandbox Code Playgroud)

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

jjn*_*guy 39

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

在下面的代码中,修改Apple模型对象,以便seeds不自动解析该字段.将变量声明更改为:

private List<Seed> seeds_funkyName;
Run Code Online (Sandbox Code Playgroud)

这是代码:

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;
    }
});
Run Code Online (Sandbox Code Playgroud)

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

  • 不要在适配器内部初始化Gson!请改用arg2.fromJson(...)! (2认同)