[英]Response as JSON (Retrofit + Android + PHP Slim Framework)
我正在使用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中添加了该异常。
您的Json回应
{成功:'是'}
是无效的。 键和(字符串)值必须用双引号引起来。
请确保您的回复用双引号引起来:
{“成功”:“是”}
或尝试以下方法:
$response = array();
$response["success"] = "yes";
echo json_encode($response);
注意:您可以在以下网址查看任何JSON字符串是否有效: https : //jsonlint.com/或https://jsonformatter.curiousconcept.com/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.