想象一下,如果我有以下JSON
=FILTER(A2:A,B2:B="FAIL",C2:C="P0")
我的课程如下
{"game":"football", "people":"elevent"}
{"game":"badminton", "people":"two"}
我可以对我的Json进行反序列化,如下所示
class Sport {
String game;
String people;
}
但是,如果我的JSON只是
Sport mySport = Gson().fromJson(json, Sport.class);
我希望自动将{"game":"football"}
{"game":"badminton"}
初始化为" elevent"或者"两个",等待第一个字段。有没有办法配置我的GsonBuilder()以在反序列化期间自动实现?
答案 0 :(得分:1)
您可以创建自定义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);
答案 1 :(得分:0)
我的回答不是这个问题的最佳答案,因为我简化了问题,另一个答案会更好地解决这个问题。
但是对于更复杂的场景,我在下面的回答会有所帮助。它基本上是在GSon转换后进行后处理的。
我最终使用Gson转换后处理。
class Sport implements PostProcessingEnabler.PostProcessable {
String game;
String people;
@Override
public void gsonPostProcess() {
// The below is something simple.
// Could have more complicated scneario.
if (game.equals("football")) {
people = "elevant";
} else if (game.equals("badminton")) {
people = "two";
}
}
}
class PostProcessingEnabler implements TypeAdapterFactory {
public interface PostProcessable {
void gsonPostProcess();
}
public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
final TypeAdapter<T> delegate = gson.getDelegateAdapter(this, type);
return new TypeAdapter<T>() {
public void write(JsonWriter out, T value) throws IOException {
delegate.write(out, value);
}
public T read(JsonReader in) throws IOException {
T obj = delegate.read(in);
if (obj instanceof PostProcessable) {
((PostProcessable) obj).gsonPostProcess();
}
return obj;
}
};
}
}
致敬https://blog.simplypatrick.com/til/2016/2016-03-02-post-processing-GSON-deserialization/