com.google.gson.JsonPrimitive无法转换为com.google.gson.JsonObject [英] com.google.gson.JsonPrimitive cannot be cast to com.google.gson.JsonObject
问题描述
我有一个来自PHP的json列表:
I have a json list like this from PHP:
$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上,我可以显示如下结果:
From Android i can show the result like this:
JsonParser jsonParser = new JsonParser();
JsonObject res = (JsonObject) jsonParser.parse(new Gson().toJson(response.body()));
Log.w("Return", response.body().toString());
到目前为止一切正常,但是当我尝试从返回的结果中创建新的Json Object
时,出现以下错误消息:
All works fine until now, but when i try to make a new Json Object
from the returned results, i get this error message:
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());
请修复吗?
推荐答案
首先,修复您的PHP.
First, fix your 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字符串.
You don't need to encode an already valid JSON string.
一切正常
您从未在那里使用过res
.您按原样打印了响应正文.
You never used res
there. You printed the response body as-is.
Log.w("Return", response.body().toString());
这看起来是错误的.响应已经是一个JSON字符串,因此toJson
不是必需的.
This looks wrong. The response is already a JSON string, so toJson
wouldn't be necessary.
jsonParser.parse(new Gson().toJson(response.body()));
您的错误是"JsonPrimitive",在这种情况下是字符串,它不是JSON对象.
Your error is the "JsonPrimitive" in this case is a String, which is not a JSON object.
您应该这样做
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");
或者,您将需要进行POJO并反序列化数据列表.
Alternatively, you will need to make a POJO and deserialize your data list.
class Data {
String test, message;
}
这篇关于com.google.gson.JsonPrimitive无法转换为com.google.gson.JsonObject的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!