android - GSON 解析 JSON 字符串
问题描述
我正在尝试通过 android 中的 gson 从 php 解析 json 字符串,但不断出现错误
在 php 脚本中我有
return json_encode(["valid"=>true,"token"=>$tokenUser->token]);
在我的android响应方法中,我有
void onApiResponse(String response){
Log.i("test", response) //gives "{\"valid\":false,\"token\":null}"
//using gson below
VerificationResponse verificationResponse = new Gson().fromJson(response,VerificationResponse.class);
}
我的验证响应类有
private class VerificationResponse{
private Boolean valid;
private String token;
public Boolean getValid() {
return valid;
}
public String getToken() {
return token;
}
}
verificationResponse.getValid()
每当我尝试通过获取错误来访问 isValid getter
com.google.gson.JsonSyntaxException: java.lang.IllegalStateException:
Expected BEGIN_OBJECT but was STRING
我在这缺少什么?
解决方案
String Json_Header = "Content-Type: application/json;charset=UTF-8";
String Query_Header = "Content-Type: application/x-www-form-urlencoded";
API接口
@POST("Get_Watch_List")
@Headers({Query_Header})
Call<String> GetWatchList(@Query("Token") String Token);
呼叫服务
ApiInterface apiService = ApiClient.getClient().create(ApiInterface.class);
Call<String> call = apiService.GetWatchList(GlobalApp.Token);
call.enqueue(new Callback<String>() {
@Override
public void onResponse(Call<String> call, Response<String> response) {
try {
Gson gson = new Gson();
VerificationResponse verificationResponse = gson.fromJson(response.body(), VerificationResponse.class);
if (verificationResponse.getValid().equals("true")) {
// here your code
}
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public void onFailure(Call<String> call, Throwable t) {
}
});
推荐阅读
- python - 每个日期的熊猫选择最小和最大时间行
- c++ - 如何将 MySQL 与 codeblocks IDE 集成
- r - 来自 R 中不同列的样本
- javascript - Kendo UI Chart 中的分组和堆叠数据
- mysql - MySQL如何使用多字段索引进行中间索引字段OR的查询?
- python - 比较大列表中的字符串,但不能在 Python 中使用 set
- share - Linkedin:共享网址摘要未出现
- python - Django - 将 InMemoryUploadedFile 发布到外部 REST api
- rstudio - 如何在执行简单操作的同时保持 Rstudio 中的数字分数格式?
- fortran - 为什么在 Fortran 中作为参数传递时,内部函数 exp 无法工作?