簡體   English   中英

無法將 JsonNull 轉換為 JsonObject

[英]Can't cast JsonNull to JsonObject

我想將一個原始屬性從一個 JsonObject 復制到另一個

JsonObject propertyToBeCopied = source.getAsJsonObject(propertyName);

但我總是遇到這個異常:

com.google.gson.JsonNull cannot be cast to com.google.gson.JsonObject

根據文檔,應該可以進行演員表,還是我錯了?

根據文檔JsonNullJsonElement但不是JsonObject (它本身就是JsonElement )。 使用

JsonElement element = source.get(propertyName);
if (!(element instanceof JsonNull)) {
    JsonObject propertyToBeCopied = (JsonObject) element;
}

如果JsonElement ,則將返回一個JsonElement轉換為JsonObjectJsonNull

根據API 參考JsonNull派生自JsonElement不是JsonObject ,所以我不知道該轉換如何有效。

您是否考慮過使用json-simple而不是 gson? 作為一般規則,我發現它比其他 json 框架更方便使用,盡管它當然沒有 gson 提供的很多額外功能。 但是,如果您使用 gson 所做的只是解析 json,則可能值得切換到更簡單的庫。

JsonElement element = source.get(propertyName);
if (!(element.isJsonNull())) {
    JsonObject propertyToBeCopied = (JsonObject) element;
}

使用JsonNull或使用instanceOf運算符哪一個會有更好的性能?

如果輸出沒有 Response 數組,則可能會引發此錯誤。

JsonObject playListObject = (JsonObject) parser.parse(output);

JsonArray playListInformationArray = playListObject.getAsJsonArray("Response");

暫無
暫無

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

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