Gson - Same field name, different types

前端 未结 2 590
名媛妹妹
名媛妹妹 2020-12-04 22:28

I asked this in a different question today but I\'m afraid that won\'t get any solution because of how it was phrased.

I have a json input that has the following dat

2条回答
  •  -上瘾入骨i
    2020-12-04 22:56

    In my situation, the field with same name is "data":{} or "data":[array_with_real_data]. So the code from accepted answer need to be modified slightly, like this:

    @Override
    public MyClass deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
            throws JsonParseException {
        MyClass bean = new Gson().fromJson(json, MyClass.class);
        JsonObject jsonObject = json.getAsJsonObject();
    
        if (jsonObject.has("data")) {
            JsonArray array = jsonObject.getAsJsonArray("data");
            if (array != null && !array.isJsonNull()) {
                List data = new Gson().fromJson(array, new TypeToken>() {}.getType());
                bean.realData = data;
            }
        }
        return bean ;
    }
    

    hope that helps.

提交回复
热议问题