【问题标题】:Retrofit2 Error : java.lang.IllegalStateException: Expected BEGIN_OBJECT but was STRING at line 1 column 1 path $Retrofit2 错误:java.lang.IllegalStateException:预期 BEGIN_OBJECT 但在第 1 行第 1 列路径 $
【发布时间】:2018-01-10 02:31:23
【问题描述】:

我正在尝试将 arraylist 传递给 php 以执行一些操作。当我用邮递员进行测试时,我得到了以下响应..

{"correct_answers":"2","total_question":"5","message":"太棒了!您需要至少获得 60% 的分数才能进入下一个级别.."," message_percentage":"40","saved_message":"success"}

enter image description here

但是当我尝试发送请求时,我收到了这个错误..

java.lang.IllegalStateException:应为 BEGIN_OBJECT,但在第 1 行第 1 列路径 $

这是我的api接口

@POST("questions.php")

@FormUrlEncoded

Call<QuestionResult> correctQuestionData(@Field("tag") String tag, @Field("str_question_answer[]") ArrayList<QuestionAnswers> str_question_answer,
                                         @Field("student_id")  String student_id, @Field("level") String level);

【问题讨论】:

  • 请显示“QuestionResult”类。我认为你弄错了。

标签: php android json retrofit2


【解决方案1】:

问题是Gson期待一个对象,但接收到一个String,这是因为格式 > JSON 的可能是错误的。 JSON 必须以

开头
{

请检查 JSON 格式。

编辑: 查看查询的参数,我认为您发送的是其他参数而不是您在邮递员中放入的参数,并且服务器以字符串而不是 JSON 响应

【讨论】:

  • {"correct_answers":"2","total_question":"5","message":"太棒了!您需要获得至少 60% 的分数才能进入下一个级别.." ,"message_percentage":"40","saved_message":"success"} 这是我用邮递员测试时收到的格式。
  • echo json_encode([ "correct_answers" => count($correct_answers)."", "total_question" => $total_question."", "message" => $results["message"], "message_percentage" => $percentage."", "message"=> $results["message"], "saved_message" =>$results["saved_message"] ]);这是我在 php 代码中定义的
  • 在获取数据时尝试从浏览器复制并粘贴结果或在 reotrofit2 中的“onFailure”函数中设置断点以了解答案。可能是您发送了错误的参数并且不是相同的答案
【解决方案2】:

我认为你在 QuestionResult 类中犯了错误。它的格式应该像

public class QuestionResult{

public String correct_answers;
public String total_question;
public String message;  
public String message_percentage;
public String saved_message;    

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-05-12
    • 1970-01-01
    • 2017-07-04
    • 2020-11-09
    • 1970-01-01
    • 1970-01-01
    • 2020-03-10
    相关资源
    最近更新 更多