【问题标题】:Retrofit2 and converter-gson: Expected BEGIN_OBJECT but was STRING at line 1 column 1 path $Retrofit2 和转换器-gson:预期 BEGIN_OBJECT 但在第 1 行第 1 列路径 $
【发布时间】:2017-12-21 22:48:28
【问题描述】:

我已经阅读了针对此问题的先前解决方案mostly this one,但没有一个对我有用。 :(。在调试时,我发现了来自改造的原始请求数据,如下图所示,我突出显示了 2 个部分:

这里是第一个突出显示的部分,以原始 json 格式显示我的改造请求

{
  "operation": "register",
  "studentModel": {
    "batch_id": "cseuui",
    "dept_code": "CSE",
    "password": "p",
    "student_address": "tpc",
    "student_email": "foc@gxs.bv",
    "student_id": "tyjvc",
    "student_name": "jak",
    "student_phone": "87532"
  }
}

但这给了我第二个突出显示的错误部分:

Expected BEGIN_OBJECT but was STRING at line 1 column 1 path $

但是使用 postman 我能够成功地将这个原始 json 插入到数据库中。

{
  "operation": "register",
  "studentModel": {
    "batch_id": "cseuui",
    "dept_code": "CSE",
    "password": "p",
    "student_address": "tpc",
    "student_email": "foc@gxs.bv",
    "student_id": "tyjvc",
    "student_name": "jak",
    "student_phone": "87532"
  }
}

这意味着我的服务器端没问题。
我还有什么遗漏的吗?
我在下面给出我的一些代码,

Retrofit2 和 Gson 依赖:

compile 'com.squareup.retrofit2:retrofit:2.1.0'  
compile 'com.squareup.retrofit2:converter-gson:2.1.0'

StudentModel.java

Server request and response

Retrofit Client and ApiInterface

最后

Registration Method

由于我的服务器端与邮递员完美配合,我在这里缺少什么。请告诉我。

【问题讨论】:

  • 你能分享一下你的邮递员回复成功失败吗?
  • 当我从 Postman 提交时收到此响应表单服务器 {"result":"success","message":"Student Registered Successful!"}
  • 试试我的更新答案

标签: java android json gson retrofit2


【解决方案1】:

最后我解决了这个问题,只是将学生模型类变量名更改为我的数据库列名,并且我还删除了类定义中的@SerializedName("result") @Expose 映射。 实际上数据库列名与我的类变量不匹配。 谢谢大家,辛苦了。

【讨论】:

    【解决方案2】:

    改造获得无效的 JSON 响应

    尝试从服务器的这个字符串Fromat中发送响应

             Gson gson = new Gson();
             response=gson.toJson(courseList);
             JsonObject myObj = new JsonObject();
    
             myObj.addProperty("operation", "register");
    
             myObj.add("studentModel",data);
    
             response = myObj.toString();
    
    return responce;
    

    改造建造者

    retrofit =new Retrofit.Builder()
                        .baseUrl(BASE_URL)
                        .addConverterFactory(GsonConverterFactory.create())
                        .build();
    

    【讨论】:

    • 谢谢,但我试图只提交到服务器 -> { "operation": "register", "studentModel": { "batch_id": "cseuui", "dept_code": "CSE", "password": "p", "student_address": "tpc", "student_email": "foc@gxs.bv", "student_id": "tyjvc", "student_name": "jak", "student_phone": "87532" } } 在调试应用程序时来自 gson,但这给出了 illigalState 异常。
    【解决方案3】:

    您正在尝试访问数组,但 Gson 在第一行找到了一个字符串。

    所以你需要更改模型类。

    StudentModel.java

    ` 公共类 StudentModel {

    private String operation;
    private Student student;
    
    public Rootjava(String operation, Student student) {
        this.operation = operation;
        this.student = student;
    }
    
    public String getOperation() {
        return operation;
    }
    
    public void setOperation(String operation) {
        this.operation = operation;
    }
    
    public Student getStudent() {
        return student;
    }
    
    public void setStudent(Student student) {
        this.student = student;
    }
    
    @Override
    public String toString() {
        return "studentModel{" +
                "operation='" + operation + '\'' +
                ", student=" + student +
                '}';
    }
    
    private class Student{
        @SerializedName("dept_code")
        private String deptCode;
        @SerializedName("student_name")
        private String studentName;
        private String password;
        @SerializedName("batch_id")
        private String batchId;
        @SerializedName("student_phone")
        private String studentPhone;
        @SerializedName("student_address")
        private String studentAddress;
        @SerializedName("student_id")
        private String studentId;
        @SerializedName("student_email")
        private String studentEmail;
    
        public Student(String deptCode, String studentName,
                       String password, String batchId,
                       String studentPhone, String studentAddress,
                       String studentId, String studentEmail) {
            this.deptCode = deptCode;
            this.studentName = studentName;
            this.password = password;
            this.batchId = batchId;
            this.studentPhone = studentPhone;
            this.studentAddress = studentAddress;
            this.studentId = studentId;
            this.studentEmail = studentEmail;
        }
    
        public String getDeptCode() {
            return deptCode;
        }
    
        public void setDeptCode(String deptCode) {
            this.deptCode = deptCode;
        }
    
        public String getStudentName() {
            return studentName;
        }
    
        public void setStudentName(String studentName) {
            this.studentName = studentName;
        }
    
        public String getPassword() {
            return password;
        }
    
        public void setPassword(String password) {
            this.password = password;
        }
    
        public String getBatchId() {
            return batchId;
        }
    
        public void setBatchId(String batchId) {
            this.batchId = batchId;
        }
    
        public String getStudentPhone() {
            return studentPhone;
        }
    
        public void setStudentPhone(String studentPhone) {
            this.studentPhone = studentPhone;
        }
    
        public String getStudentAddress() {
            return studentAddress;
        }
    
        public void setStudentAddress(String studentAddress) {
            this.studentAddress = studentAddress;
        }
    
        public String getStudentId() {
            return studentId;
        }
    
        public void setStudentId(String studentId) {
            this.studentId = studentId;
        }
    
        public String getStudentEmail() {
            return studentEmail;
        }
    
        public void setStudentEmail(String studentEmail) {
            this.studentEmail = studentEmail;
        }
    
        @Override
        public String toString() {
            return "Student{" +
                    "deptCode='" + deptCode + '\'' +
                    ", studentName='" + studentName + '\'' +
                    ", password='" + password + '\'' +
                    ", batchId='" + batchId + '\'' +
                    ", studentPhone='" + studentPhone + '\'' +
                    ", studentAddress='" + studentAddress + '\'' +
                    ", studentId='" + studentId + '\'' +
                    ", studentEmail='" + studentEmail + '\'' +
                    '}';
        }
    }
    

    }`

    使用这个模型类。

    你可以使用插件来生成这个 POJO 类。

    【讨论】:

    • 现在我正在尝试更改模型类,但如果是这样的话,我将不得不为学生模型使用 2 个不同的模型类。让我看看会发生什么。
    【解决方案4】:

    试试这个:

    您的接收字符串而不是 JsonObject。像此映射一样更改您的 ServerResponse 并将标头添加为 'application/json'

    1.添加header header.put("Content-Type", "application/json");

    private void registerProcess(String studentName, String studentAddress, String studentEmail, String studentPhone, String department, String batch_id, String student_id, String rePassword) {
    
            APIInterface appInterface = ApiClient.getClient().create(APIInterface.class);
    
            StudentModel student = new StudentModel();
            student.setStudent_name(studentName);
            student.setStudent_address(studentAddress);
            student.setStudent_email(studentEmail);
            student.setStudent_phone(studentPhone);
            student.setDept_code(department);
            student.setBatch_id(batch_id);
            student.setStudent_id(student_id);
            student.setPassword(rePassword);
    
            Log.e(TAG,student.toString());
    
            ServerRequest request = new ServerRequest();
    
    
            Map<String, String> header = new HashMap<>();
            header.put("Content-Type", "application/json");
    
            request.setOperation(Config_Ref.REGISTER_OPERATION);
            request.setStudentModel(student);
    
            Call<ServerResponse> response = appInterface.operation(request,header);
    
            response.enqueue(new Callback<ServerResponse>() {
                @Override
                public void onResponse(Call<ServerResponse> call, Response<ServerResponse> response) {
    
                    if(response.isSuccessful()){
    
                        ServerResponse resp = response.body();
                        Toast.makeText(RegisterActivity.this, resp.getMessage()+" success", Toast.LENGTH_SHORT).show();
                        Log.e(TAG,resp.getMessage()+" success");
                    }else{
                        Toast.makeText(RegisterActivity.this, response.message()+" not success", Toast.LENGTH_SHORT).show();
                        Log.e(TAG,response.message()+" not success");
                    }
                   /* Snackbar.make(fview, resp.getMessage(), Snackbar.LENGTH_LONG).show();*/
    
                    //pDialog.dismiss();
                }
    
                @Override
                public void onFailure(Call<ServerResponse> call, Throwable t) {
                    /*Snackbar.make(fview, t.getLocalizedMessage(), Snackbar.LENGTH_LONG).show();*/
                    Toast.makeText(RegisterActivity.this, t.getLocalizedMessage()+" failed"+call.toString(), Toast.LENGTH_SHORT).show();
    
                    Log.e(TAG,t.getLocalizedMessage()+" failed");
                }
            });
    
    
        }
    

    2.ApiInterface.java

    将标头添加为 json 格式 公共接口 ApiInterface {

        @POST("/iuk/api/credentials")
        Call<ServerResponse> operation(@Body ServerRequest request,@HeaderMap Map<String, String> header);
       }
    

    3.ServerResponse.java

        public class ServerResponse {
    
        @SerializedName("result")
        @Expose
        private String result;
        @SerializedName("message")
        @Expose
        private String message;
    
        public String getResult() {
        return result;
        }
    
        public void setResult(String result) {
        this.result = result;
        }
    
        public String getMessage() {
        return message;
        }
    
        public void setMessage(String message) {
        this.message = message;
        }
    
        }
    

    ApiClient.Java

    public class ApiClient {
    
        private static final String BASE_URL = "https://xyz.000webhostapp.com";
        private static Retrofit retrofit = null;
    
    
        public static Retrofit getClient() {
            if (retrofit == null) {
                HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
                interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
                OkHttpClient client = new OkHttpClient.Builder().addInterceptor(new Interceptor() {
                 @Override
                public Response intercept(Chain chain) throws IOException {
                    Request.Builder requestBuilder = chain.request().newBuilder();
                    requestBuilder.header("Content-Type", "application/json");
                    return chain.proceed(requestBuilder.build());
                   }
                   })
                    .connectTimeout(30, TimeUnit.MINUTES)
                    .readTimeout(30, TimeUnit.MINUTES)
                    .build();
    
                retrofit = new Retrofit.Builder()
                        .baseUrl(BASE_URL)
                        .client(client)
                        .addConverterFactory(GsonConverterFactory.create())
                        .build();
            }
            return retrofit;
        }
    
    }
    

    依赖关系

    compile 'com.squareup.retrofit2:retrofit:2.3.0'
    compile 'com.google.code.gson:gson:2.8.2'
    compile 'com.squareup.retrofit2:converter-gson:2.3.0'
    compile 'com.squareup.okhttp3:okhttp:3.9.0'
    compile 'com.squareup.okhttp3:logging-interceptor:3.9.0'    
    

    【讨论】:

    • Same result ,什么都没有发生 IlligalState 异常。
    • 是的,Ok http inceptor log 有同样的例外。 ://
    • 但是表单 Postman 可以成功提交{"operation":"register","studentModel":{"batch_id":"CSE0987","dept_code":"CSE","password":"p","student_address":"assaman, bf","student_email":"alo@ma.li","student_id":"CSE086433","student_name":"jack","student_phone":"0975438"}}
    • @MohammadAbsJabed 我更新了一次答案检查..只需在ApiClient.java 中添加Request.Builder
    • ` Request.Builder requestBuilder = chain.request().newBuilder(); requestBuilder.header("Content-Type", "application/json"); return chain.proceed(requestBuilder.build());`
    【解决方案5】:

    创建模型类简单而不是列表类型。

    之后创建一个 String 变量操作并创建 studentModel 的内部类。

    public class Main{
    
        @SerializeName("operation")
        private String operation;
    
        @SerializeName("StudentModel")
        private StudentModel studentModel;
    
    }
    

    然后生成getter setter

    【讨论】:

    • 这是我对 server request 模型类所做的。
    • StudentModel 作为内部类工作,其他参数将在此类中定义
    • @SerializedName("id") private int id; @SerializedName("chapterName") 私有字符串章节名称; @SerializedName("subject") private StudentSubject studentSubject;
    猜你喜欢
    • 1970-01-01
    • 2017-05-12
    • 2018-01-10
    • 1970-01-01
    • 1970-01-01
    • 2018-01-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多