簡體   English   中英

序列化/反序列化POJO包含帶有GSON的特殊枚舉(不是字符串的枚舉)

[英]Serialize/Deserialize a POJO contain a speciel Enum (not Enum of String) with GSON

我需要序列化/反序列化一個包含特殊Enum的POJO( 而不是String的Enum )。 我發現很多帶有字符串枚舉的示例,但不是我的情況。

我閱讀了Gson文檔,並且開始使用implements JsonDeserializer<T>, JsonSerializer<T>解決方案

public class ApplicationError {

    private static final long serialVersionUID = 1L;

    private final ErrorCode code;

    private final String description;

    private final URL infoURL;

    ....
}

public enum ErrorCode {
    INVALID_URL_PARAMETER(HttpStatus.BAD_REQUEST, 20, "Invalid URL parameter value"),
    MISSING_BODY(HttpStatus.BAD_REQUEST, 21, "Missing body"),
    INVALID_BODY(HttpStatus.BAD_REQUEST, 22, "Invalid body")
}

public class ErrorCodeDeserializer implements JsonDeserializer<ErrorCode> /*, JsonSerializer<ErrorCode> */{

    @Override
    public ErrorCode deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
            throws JsonParseException {
        ErrorCode[] scopes = ErrorCode.values();
        for (ErrorCode scope : scopes) {
            System.out.println("--------->" + scope + "   " + json.getAsString());
            if (scope.equals(json.getAsString())) {
                return scope;
            }
        }
        return null;
    }

    /*
    @Override
    public JsonElement serialize(ErrorCode arg0, Type arg1, JsonSerializationContext arg2) {
        ???
    }*/
}

...
ApplicationError applicationError = new ApplicationError(ErrorCode.INVALID_URL_PARAMETER,
                    "Application identifier is missing");
....
GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.registerTypeAdapter(ErrorCode.class, new ErrorCodeDeserializer());
Gson gson = gsonBuilder.create();
gson.toJson(applicationError)

我的結果是:

{“代碼”:“ INVALID_URL_PARAMETER”,“描述”:“應用程序標識符丟失”}

代替:

{“代碼”:“ 20”,“消息”:“無效的URL參數值”,“描述”:“缺少應用程序標識符”}

編輯1

我嘗試:

@Override
public JsonElement serialize(ErrorCode src, Type typeOfSrc, JsonSerializationContext context) {
    JsonArray jsonMerchant = new JsonArray();
    jsonMerchant.add("" + src.getCode());
    jsonMerchant.add("" + src.getMessage());
    return jsonMerchant;
}

但我的結果是:

{"code":["20","Invalid URL parameter value"],"description":"Application identifier is missing"}

編輯2

我嘗試:

@Override
public JsonElement serialize(ErrorCode src, Type typeOfSrc, JsonSerializationContext context) {
    JsonObject result = new JsonObject();
    result.add("code", new JsonPrimitive(src.getCode()));
    result.add("message", new JsonPrimitive(src.getMessage()));
    return result;
}

但我的結果是:

{"code":{"code":20,"message":"Invalid URL parameter value"},"description":"Application identifier is missing"}

現在,我只想將"code":{"code":20,"message":"Invalid URL parameter value"}更改為"code":20,"message":"Invalid URL parameter value"

通常,由於以下幾個原因,這是一個壞主意:

  • 如果在流模式下讀取平面屬性(確保屬性的順序保持不變),則需要對反序列化器(如果需要)進行復雜處理。
  • 否則,您需要使用ErrorCode枚舉為每個類編寫一個特殊的類型適配器,並且需要為每個類自定義JsonSerializer / JsonDeserializer
  • 反序列化ErrorCode對我完全沒有意義。
  • Gson不允許將對象“拉平”到彼此之間。

在最簡單的實現中,我想說的是您可能想要使用以下內容

final class FlatErrorCodeTypeAdapter
        extends TypeAdapter<ErrorCode> {

    private FlatErrorCodeTypeAdapter() {
    }

    @Override
    public void write(final JsonWriter out, final ErrorCode errorCode)
            throws IOException {
        // very bad idea - the serializer may be in a bad state and we assume the host object is being written
        out.value(errorCode.code);
        out.name("message");
        out.value(errorCode.message);
    }

    @Override
    public ErrorCode read(final JsonReader in)
            throws IOException {
        // now fighting with the bad idea being very fragile assuming that:
        // * the code field appears the very first property value
        // * we ignore the trailing properties and pray the host object does not have "message" itself
        // * no matter what "message" is -- it simply does not have sense
        final int code = in.nextInt();
        return ErrorCode.valueByCode(code);
    }

}

然后在您的代碼中是這樣的:

final class ApplicationError {

    @JsonAdapter(FlatErrorCodeTypeAdapter.class)
    final ErrorCode code;
    final String description;

    ApplicationError(final ErrorCode code, final String description) {
        this.code = code;
        this.description = description;
    }

}

使用示例:

private static final Gson gson = new Gson();

...

final ApplicationError before = new ApplicationError(ErrorCode.INVALID_URL_PARAMETER, "Application identifier is missing");
final String json = gson.toJson(before);
System.out.println(json);
final ApplicationError after = gson.fromJson(json, ApplicationError.class);
System.out.println(before.code == after.code);
System.out.println(before.description.equals(after.description));

輸出:

{"code":20,"message":"Invalid URL parameter value","description":"Application identifier is missing"}
true
true

我仍然認為這是一個非常脆弱的解決方案,我只建議您重新設計ApplicationError並自己“展平” ErrorCode

final class ApplicationError {

    final int code;
    final String message;
    final String description;

    ApplicationError(final ErrorCode errorCode, final String description) {
        this.code = errorCode.code;
        this.message = errorCode.message;
        this.description = description;
    }

    ...

    final ErrorCode resolveErrorCode() {
        final ErrorCode errorCode = ErrorCode.valueByCode(code);
        if ( !errorCode.message.equals(message) ) {
            throw new AssertionError('wow...');
        }
        return errorCode;
    }

}

使用后者,您甚至不需要以任何方式配置Gson

暫無
暫無

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

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