java.lang.IllegalStateException:预期的BEGIN_OBJECT

时间:2019-02-27 09:25:42

标签: android json gson

数据库上的数据发布。它给出结果Json格式。

{"response":"exist"}

当使用Retrofit库获得响应并使用GSON进行json解析时,它会继续使用OnFailure方法并给出错误。

call.enqueue(new Callback<Register>() {
           @Override
           public void onResponse(Call<Register> call, Response<Register> response) {


               if (response.body().equals("ok")){

                   Toast.makeText(MainActivity.this, "Registration is Successfully", Toast.LENGTH_SHORT).show();

               }else if (response.body().equals("exiest")){

                   Toast.makeText(MainActivity.this, "Already Exiest", Toast.LENGTH_SHORT).show();

               }else if(response.body().equals("error")){

                   Toast.makeText(MainActivity.this, "Registration Error", Toast.LENGTH_SHORT).show();

               }
           }

           @Override
           public void onFailure(Call<Register> call, Throwable t) {

               Toast.makeText(MainActivity.this, t.getMessage(), Toast.LENGTH_SHORT).show();

           }
       });

错误是:

com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was STRING at line 1 column 1 path $

它如何解决其“请指导我”。

2 个答案:

答案 0 :(得分:0)

您解析的响应错误。及其exist,您正在比较exiest

像这样更改您的解析

if (response.body().getResponse().equals("ok")){

                   Toast.makeText(MainActivity.this, "Registration is Successfully", Toast.LENGTH_SHORT).show();

               }else if (response.body()..getResponse().equals("exist")){

                   Toast.makeText(MainActivity.this, "Already Exiest", Toast.LENGTH_SHORT).show();

               }else if(response.body().getResponse().equals("error")){

                   Toast.makeText(MainActivity.this, "Registration Error", Toast.LENGTH_SHORT).show();

               }

答案 1 :(得分:0)

您解析的数据错误。如Callback所示,在Register模型类中改装转换响应,您应该从中读取值。

Register register= response.body();
if (register.getResponse().equals("ok")){
   Toast.makeText(MainActivity.this, "Registration is Successfully", Toast.LENGTH_SHORT).show();
 }else if (register.getResponse().equals("exist")){
   Toast.makeText(MainActivity.this, "Already Exist", Toast.LENGTH_SHORT).show();
 }else if(register.getResponse().equals("error")){
    Toast.makeText(MainActivity.this, "Registration Error", Toast.LENGTH_SHORT).show();
 }

Register.java

public class Register {
    @SerializedName("response")
    @Expose
    private String response;
    public String getResponse() {
        return response;
    }
    public void setResponse(String response) {
        this.response = response;
    }
}