无法将JsonNull转换为JsonObject [英] Can't cast JsonNull to JsonObject

查看:1322
本文介绍了无法将JsonNull转换为JsonObject的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从一个JsonObject复制一个primitve属性到另一个jsonObject propertyToBeCopied = source.getAsJsonObject(propertyName);


$ b

但我总是遇到这种异常情况:



com.google .gson.JsonNull不能转换为com.google.gson.JsonObject



根据文档,应该可以执行转换,或者我错了?

根据 docs JsonNull JsonElement 但不是 JsonObject (它本身就是一个 JsonElement )。使用

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

会返回一个 JsonElement 如果它不是类型 JsonNull


,它将被转换为 JsonObject

I want to copy one primitve property from one JsonObject to another

JsonObject propertyToBeCopied = source.getAsJsonObject(propertyName);

but I always run into this exception:

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

According to the documentation it should be possible to do the cast, or am I wrong?

解决方案

According to the docsJsonNull is a JsonElement but not a JsonObject (which is itself a JsonElement). Using

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

would return a JsonElement that is casted to JsonObject if it is not of the type JsonNull.

这篇关于无法将JsonNull转换为JsonObject的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆