如何做条件Gson反序列化默认值 [英] How to do conditional Gson deserialization default value

查看:1093
本文介绍了如何做条件Gson反序列化默认值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

想象一下,如果我有以下JSON

Imagine if I have the following JSON

{"game":"football", "people":"elevent"}
{"game":"badminton", "people":"two"}

我的课程如下

class Sport {
    String game;
    String people;
}

我可以对我的Json进行反序列化,如下所示

I could do a deserialize of my Json as below

Sport mySport = Gson().fromJson(json, Sport.class);

但是,如果我的JSON只是

However, if my JSON is only

{"game":"football"}
{"game":"badminton"}

我希望它能自动将初始化为elevent或two,等待第一个字段。有没有办法配置我的GsonBuilder()以在反序列化期间自动实现?

I would like it to automatically initialize people to "elevent" or "two", pending of the first field. Is there a way to configure my GsonBuilder() to have that achieve automatically during deserialization?

推荐答案

您可以创建自定义 JsonDeserializer

public class SportDeserializer implements JsonDeserializer<Sport> {
    @Override
    public Sport deserialize(final JsonElement json, final Type typeOfT, final JsonDeserializationContext context) throws JsonParseException {
        JsonObject jsonObject = (JsonObject) json;

        String game = jsonObject.get("game").getAsString();
        JsonElement nullablePeople = jsonObject.get("people");
        String people = nullablePeople == null ? null : nullablePeople.getAsString();

        if (people == null || people.isEmpty()) {
            if (game.equals("football")) {
                people = "elevent";
            }
            else if (game.equals("badminton")) {
                people = "two";
            }
        }

        Sport sport = new Sport();
        sport.game = game;
        sport.people = people;

        return sport;
    }
}

然后使用自定义 JsonDeserializer

GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.registerTypeAdapter(Sport.class, new SportDeserializer());
Gson gson = gsonBuilder.create();
Sport sport = gson.fromJson(jsonString, Sport.class);

这篇关于如何做条件Gson反序列化默认值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆