响应为 JSON(Retrofit + Android + PHP Slim Framework)

Response as JSON (Retrofit + Android + PHP Slim Framework)

我正在使用 PHP Slim 框架为 Android 应用程序构建 REST API。

我在应用程序中 post body,它运行良好并向 MySQL 添加数据。但是我的反应有问题。

我的回复JSON模型很简单;

{success:'yes'}

当我尝试在添加数据后获得响应时,Retrofit 会使用 onFailure 方法。但添加数据效果很好。我不知道我错过了哪里。这是我的代码;

PHP 超薄框架文件

$response->withHeader('Content-Type', 'application/json');
    $response->getBody()->write("{success:'yes'}");
    return $response;

} catch (PDOException $e) {
    echo '{"error": {"text": ' . $e->getMessage() . '}';
}

Android 响应模型

public class Response_Success {

@SerializedName("success")
@Expose
String success;

public Response_Success(String success) {
    this.success = success;
}

public String getSuccess() {
    return success;
}

public void setSuccess(String success) {
    this.success = success;
}

界面Class

public interface API_Service {
@Headers("content-type: application/json")
@POST("api/user/add")
Call<Response_Success> addFacebookUser(@Body UserFacebook userFacebook);}

API 在MainActivity中调用

API_Service service = Client.getRetrofitInstance().create(API_Service.class);

        Call<Response_Success> userFacebookCall = service.addFacebookUser(userNew);

        userFacebookCall.enqueue(new Callback<Response_Success>() {
            @Override
            public void onResponse(Call<Response_Success> call, Response<Response_Success> response) {
                Toast.makeText(MainActivity.this, ""+response.body().getSuccess(), Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onFailure(Call<Response_Success> call, Throwable t) {
                Toast.makeText(MainActivity.this, "was wrong", Toast.LENGTH_SHORT).show();
            }
        });

android 工作室中的调试模式;我得到 MaltFormedJsonException,但我在 try catch 中添加了该异常。

您的 Json 回复

{success:'yes'}

无效。键和(字符串)值必须用双引号引起来。

要么确保您的回复用双引号引起来:

{"success":"yes"}

或者试试这个:

$response = array();
$response["success"] = "yes";
echo json_encode($response);

注意:您可以在以下位置检查 JSON 字符串是否有效: https://jsonlint.com/ 要么 https://jsonformatter.curiousconcept.com/