想象一下,如果我有以下 JSON
{"game":"football", "people":"elevent"}
{"game":"badminton", "people":"two"}
我的类(class)如下
class Sport {
String game;
String people;
}
我可以对 Json 进行反序列化,如下所示
Sport mySport = Gson().fromJson(json, Sport.class);
但是,如果我的 JSON 只是
{"game":"football"}
{"game":"badminton"}
我希望它自动将 people
初始化为“elevent”或“two”,等待第一个字段。有没有办法配置我的 GsonBuilder() 以在反序列化期间自动实现该目标?
最佳答案
您可以创建自定义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);
关于java - 如何做条件Gson反序列化默认值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39951187/