【问题标题】:com.google.gson.JsonPrimitive cannot be cast to com.google.gson.JsonObjectcom.google.gson.JsonPrimitive 无法转换为 com.google.gson.JsonObject
【发布时间】:2017-09-24 10:58:45
【问题描述】:

我有一个来自 PHP 的这样的 json 列表:

$Json = '[{"test":"1", "message":"try it"}, 
{"test":"2", "message":"try it"}, {"test":"3", "message":"try it"} ...]';
$final = [ 'error' => '1', 'json' => json_encode($Json)];
die(json_encode($final));

在 Android 中,我可以显示如下结果:

JsonParser jsonParser = new JsonParser();
JsonObject res = (JsonObject) jsonParser.parse(new Gson().toJson(response.body()));
Log.w("Return", response.body().toString());

到目前为止一切正常,但是当我尝试从返回的结果中创建一个新的 Json Object 时,我收到以下错误消息:

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

我做了什么:

JsonObject json = (JsonObject) jsonParser.parse(new Gson().toJson(res.get("json").toString()));
Log.w("JSON", json.toString());

请问有什么办法吗?

【问题讨论】:

    标签: java android json


    【解决方案1】:

    首先,修复您的 PHP。

    $Json = array(
        array('test' => '1', 'message' => 'try it'), 
        array('test' => '2', 'message' => 'try it')
      );
    $final = array(
      'error' => '1', 
      'json' => $Json
    );
    die(json_encode($final, JSON_FORCE_OBJECT));
    

    您不需要对已经有效的 JSON 字符串进行编码。


    一切正常

    你从未在那里使用过res。您按原样打印了响应正文。

    Log.w("Return", response.body().toString());
    

    这看起来不对。响应已经是 JSON 字符串,因此不需要 toJson

    jsonParser.parse(new Gson().toJson(response.body()));
    

    您的错误是“JsonPrimitive”在这种情况下是一个字符串,它不是 JSON 对象。


    你应该这样做

    final String body = response.body().toString(); // Or use response.raw(), if want raw response string
    JsonParser jsonParser = new JsonParser();
    JsonObject res = jsonParser.parse(body).getAsJsonObject();
    Log.w("Return", res.toString());
    

    如果你想要数据,那么你可以拥有

    JsonArray data = res.getAsJsonArray("data");
    

    或者,您需要创建一个 POJO 并反序列化您的数据列表。

    class Data {
        String test, message;
    }
    

    【讨论】:

    • 感谢您的回答,在使用您的代码时,我收到了这个新错误:Not a JSON Object: "com.myapp.model.User@5a1a6fc"
    • 嗯,用户不是 JSONObject。我的回答根本不使用 User 类,所以这是不相关的
    • 我的目标是将 JSON 转换为 JsonArray 并对其进行操作,例如获取 length() ...我可以直接这样做而无需更改我的代码:JsonArray ress = res.get("JSON").getAsJsonArray();,但得到相同的错误.
    • 我相信您正在寻找 gson.fromJson(jsonString, User.class),但如果您花一点时间找到它并阅读一些示例,那它已在 Gson 文档中列出
    • 您是否偶然使用了 Retrofit?如果是这样,您不需要通过 Gson 重新映射 JSON 来转换任何内容
    猜你喜欢
    • 1970-01-01
    • 2020-12-13
    • 2019-06-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-02-02
    • 2016-06-30
    相关资源
    最近更新 更多