簡體   English   中英

遞歸類型適配器GSON

[英]Recursive Type-Adapter GSON

給出以下結構:

abstract class Message {
   Message anotherMessage;
   String attribute; //just random stuff
}

我想將以下json-string作為輸出:

 {type=Class.getSimpleName(), data=gson(Message)} 

因為Message是抽象的,可以有多種實現。 問題是,“ anotherMessage”不會具有數據的結構類型。

我的序列化實現:

public JsonElement serialize(final Message src, final Type typeOfSrc,
    final JsonSerializationContext context) {
  Gson gson = new Gson();
  JsonObject elem = new JsonObject();
  elem.addProperty("type", src != null ? src.getClass().getSimpleName() : null);
  elem.addProperty("data", src != null ? gson.toJson(src) : null);
  return elem;
}

我該如何遞歸執行此操作? 我無法獲得具有已附加的消息適配器的Gson對象(stackoverflow-exception)

在序列化/反序列化期間可以使用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);

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM