响应为JSON(改造+ Android + PHP超薄框架)

时间:2018-05-05 19:34:20

标签: java php android retrofit slim

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

我在app中发布了body,它运行良好并向MySQL添加数据。但我的回答很麻烦。

我的回答JSON模型很简单;

{success:'yes'}

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

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中添加了该异常。

1 个答案:

答案 0 :(得分:0)

您的Json回复

  

{成功: '是'}

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

要么确保您的回复是双引号:

  

{ “成功”: “是”}

或者试试这个:

public class Bug
{
    private int position;
    private String direction;

    public void initialPosition(int position ) {
        position=0;
    }

    public void initialDirection(String direction) {
        direction="right";
    }

    public void setPosition (int position) {
        this.position = position;
    }

    public int getPosition() {
        return position;
    }

    public void setDirection (String direction) {
        this.direction = direction;
    }

    public String getDirection() {
        return direction;
    }

    public void move() {
        position+=1;
    }   

    public void reverseDirection() {
        if (direction=="right") {
            direction="left";
        }
        else {
            direction="right";
        }
    }

    public String toString() {
        return "Position: " + position + " & Direction: " + direction;
    }
}

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