【问题标题】:Response as JSON (Retrofit + Android + PHP Slim Framework)响应为 JSON(改造 + Android + PHP Slim 框架)
【发布时间】:2018-10-16 00:39:46
【问题描述】:

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

我在应用程序中发布正文,它运行良好并将数据添加到 MySQL。但我的反应有问题。

我的响应 JSON 模型很简单;

{success:'yes'}

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

PHP Slim 框架文件

$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;
}

接口类

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

MainActivity 中的 API 调用

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 studio 中的调试模式;我得到 MaltFormedJsonException,但我在 try catch 中添加了该异常。

【问题讨论】:

标签: java php android retrofit slim


【解决方案1】:

你的 Json 响应

{成功:'是'}

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

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

{"成功":"是"}

或者试试这个:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-23
    • 2017-12-12
    • 2019-03-14
    • 2017-01-26
    • 2015-08-18
    • 2011-10-12
    相关资源
    最近更新 更多