在序列化/反序列化過程中,可以使用JsonSerializationContext/JsonDeserializationContext來序列化/反序列化另一個對象。
Message.java
abstract class Message {
Message anotherMessage;
String theMessage;
public Message getAnotherMessage() {
return anotherMessage;
}
public String getTheMessage() {
return theMessage;
}
}
Info.java
public class InfoMessage extends Message {
public InfoMessage(Message anotherMessage, String theMessage) {
this.anotherMessage = anotherMessage;
this.theMessage = theMessage;
}
}
Alert.java
public class AlertMessage extends Message {
public AlertMessage(Message anotherMessage, String theMessage) {
this.anotherMessage = anotherMessage;
this.theMessage = theMessage;
}
}
ErrorMessage.java
public class ErrorMessage extends Message {
public ErrorMessage(Message anotherMessage, String theMessage) {
this.anotherMessage = anotherMessage;
this.theMessage = theMessage;
}
}
個
MessageSerializer.java
public JsonElement serialize(Message src, Type typeOfSrc, JsonSerializationContext context) {
JsonObject elem = new JsonObject();
if (src == null) {
} else {
elem.addProperty("type", src.getClass().getSimpleName());
elem.addProperty("attribute", src.getTheMessage());
elem.add("data", src.anotherMessage != null ? context.serialize(src.anotherMessage, Message.class): null);
}
return elem;
}
Test.java
public static void main(String[] args) {
Gson gson = new GsonBuilder()
.registerTypeAdapter(Message.class, new MessageSerializer())
.setPrettyPrinting()
.create();
String json = gson.toJson(
new InfoMessage(
new AlertMessage(
new ErrorMessage(null, "the error message"),
"the alert message"),
"the info message"),
Message.class);
System.out.println(json);
}