在我的应用程序中,我得到一个我想要转换为JSON的字符串 要做到这一点,我使用以下内容:
JsonParser gsonTest = new JsonParser();
JsonObject toto= new
JsonParser().parse(response).getAsJsonObject();
testhash = toto.get("access_token").getAsString();
但是我收到以下错误:
java.lang.IllegalStateException: Not a JSON Object:
{
"access_token": "NmUxMjdjYjllZWNhZDBhNjNhMGJmYzE0YWE1YjIzOTM2ODkwMGI3ZmMyZDRmNDJhMGRkNGNiM2U4N2FkZTk4Yg",
"expires_in": 3600,
"token_type": "bearer",
"scope": null,
"refresh_token": "MDZkYWFlOGEwN2M0MGE1MDFmZmRhYmVlOGE0NTllMWY0NTBlY2VhZmJhYTJlM2RkM2NkNjhlZjk3M2E5ZDQxMQ",
"user": {
"id": 3,
"serverPath": "/Applications/MAMP/htdocs/SupDocAPI/Storage",
"username": "toto",
"defaultFolder": 2,
"email": "toto@gmail.com"
}
}
答案 0 :(得分:0)
响应不是正确的JSON格式。就像这个{"access_token":"NmUxMjdjYjllZWNhZDBhNjNh"}
。删除反斜杠" \"来自JSON回复。
答案 1 :(得分:0)
JSON字符串有效,但JSON数据不准确,您必须删除所有escape char back slash "\"
才能获得真实数据:
{
"access_token": "NmUxMjdjYjllZWNhZDBhNjNhMGJmYzE0YWE1YjIzOTM2ODkwMGI3ZmMyZDRmNDJhMGRkNGNiM2U4N2FkZTk4Yg",
"expires_in": 3600,
"token_type": "bearer",
"scope": null,
"refresh_token": "MDZkYWFlOGEwN2M0MGE1MDFmZmRhYmVlOGE0NTllMWY0NTBlY2VhZmJhYTJlM2RkM2NkNjhlZjk3M2E5ZDQxMQ",
"user": {
"id": 3,
"serverPath": "\/Applications\/MAMP\/htdocs\/SupDocAPI\/Storage",
"username": "toto",
"defaultFolder": 2,
"email": "toto@gmail.com"
}
}
答案 2 :(得分:0)
您尚未正确转义字符。试试这个
try {
response=response.replace("\u0022","\"");
JSONObject jsonObject=new JSONObject(response);
testhash=jsonObject.getString("access_token");
} catch (JSONException e) {
e.printStackTrace();
}
答案 3 :(得分:0)
您必须先删除反斜杠:
// Replace all \" by "
String json = response.replaceAll("\\\"", "\"");
JsonParser parser = new JsonParser();
JsonObject toto= parser.parse(json).getAsJsonObject();
testhash = toto.get("access_token").getAsString();