首页 > 解决方案 > 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

我在这缺少什么?

标签: androidjsongson

解决方案


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) {

            }
        });

推荐阅读