簡體   English   中英

當沒有數據時,空的json對象而不是null->如何使用gson反序列化

[英]Empty json object instead of null, when no data -> how to deserialize with gson

我正在嘗試使用Google的gson庫解析json數據。 但是json數據表現不佳。

一切正常后,它看起來確實像這樣:

{
    "parent": {
        "child_one": "some String",
        "child_two": "4711",
        ...
    }
}

child_one應該被解析為Stringchild_twoint 但是有時,其中一個子代沒有值,這導致空對象而不是null ,如下所示:

{
    "parent": {
        "child_one": "some String",
        "child_two": {},
        ...
    }
}

我沒有權限改變json feed,因此我必須在反序列化期間處理它。 但我迷失在這里。 如果我只是讓它解析JsonSyntaxException情況給我一個JsonSyntaxException

我想過使用自定義的JsonDeserializer 進行類似檢查每個元素是否為JsonObject檢查,是否檢查entrySet.isEmpty() 如果是,請刪除該元素。 但是我不知道如何完成迭代...

在將它傳遞給GSON之前,你不能只用NULL替換{}嗎?

使你的TypeAdapter<String>read方法如下:

public String read(JsonReader reader) throws IOException {
    boolean nextNull = false;
    while (reader.peek() == JsonToken.BEGIN_ARRAY || reader.peek() == JsonToken.END_ARRAY) {
        reader.skipValue();
        nextNull = true;
    }
    return nextNull ? null : reader.nextString();
}

解釋:當下一個標記是[] ,只需跳過它並返回null。

如果將all []替換為null直接使用String#replaceAll ,也可以替換一些真正的字符串,這可能會導致其他一些錯誤。

暫無
暫無

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

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