java com.google.gson.JsonPrimitive 不能转换为 com.google.gson.JsonObject

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/43644376/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 07:37:32  来源:igfitidea点击:

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

javaandroidjson

提问by Jis Maxi

I have a json list like this from PHP:

我有一个来自 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));

From Android i can show the result like this:

从 Android 我可以显示这样的结果:

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

All works fine until now, but when i try to make a new Json Objectfrom the returned results, i get this error message:

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

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

Here what i did:

这是我所做的:

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

Any fix please ?

请问有什么解决办法吗?

回答by OneCricketeer

First, fix your PHP.

首先,修复您的 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));

You don't need to encode an already valid JSON string.

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



All works fine

一切正常

You never used resthere. You printed the response body as-is.

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

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

This looks wrong. The response is already a JSON string, so toJsonwouldn't be necessary.

这看起来不对。响应已经是一个 JSON 字符串,所以toJson没有必要。

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

Your error is the "JsonPrimitive" in this case is a String, which is not a JSON object.

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



You should rather do this

你应该这样做

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());

If you want the data, then you can have

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

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


Alternatively, you will need to make a POJO and deserialize your data list.

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

class Data {
    String test, message;
}