Java Gson - 检查JsonElement是字符串还是JsonObject

3

我正试图通过检查一个值来使API向后兼容。

我必须确定其中一个参数是string还是JsonObject

这是我尝试过的:

if (oDevices.get(i).getAsJsonPrimitive().isJsonObject()) {
                  deviceToClean.addProperty("deviceId", oDevices.get(i).getAsJsonObject().get("name").getAsString());
              } else if(oDevices.get(i).getAsJsonPrimitive().isString()) {
                  deviceToClean.addProperty("deviceId", oDevices.get(i).getAsString());
              }

当我向API发送JsonObject时,我收到以下错误提示:
This is not a JSON Primitive.

我该如何检查oDevices.get(i)是一个JSON对象还是一个字符串?
1个回答

11

您始终获得基本值。

更改为:

if (oDevices.get(i).getAsJsonPrimitive().isJsonObject()) {

if (oDevices.get(i).isJsonObject()) {

我也会更改这个:

if(oDevices.get(i).getAsJsonPrimitive().isString()) {

变成这样:

if(oDevices.get(i).isJsonPrimitive() && oDevices.get(i).getAsJsonPrimitive().isString()) {

// ----------------^ check if it's a json primitive before getting its value

谢谢@BackSlash。我以为在简单的JsonElement上不存在isJsonObject()方法。 - TheUnreal

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接