[英]Response as JSON (Retrofit + Android + PHP Slim Framework)
I'm using PHP Slim framework to build REST API for Android application. 我正在使用PHP Slim框架为Android应用程序构建REST API。
I post body in app, it works well and add data to MySQL. 我在应用程序中发布了正文,它可以很好地工作并将数据添加到MySQL。 But I have trouble in response.
但是我在回应时遇到了麻烦。
My response JSON Model is simply; 我的响应JSON模型很简单;
{success:'yes'}
When I try to get response after data added, Retrofit works onFailure method. 当我尝试在添加数据后获得响应时,Retrofit在onFailure方法中起作用。 but adding data works well.
但是添加数据效果很好。 I don't know where I missed.
我不知道我在哪里错过。 Here are my codes;
这是我的代码;
PHP Slim Framework File PHP Slim框架文件
$response->withHeader('Content-Type', 'application/json');
$response->getBody()->write("{success:'yes'}");
return $response;
} catch (PDOException $e) {
echo '{"error": {"text": ' . $e->getMessage() . '}';
}
Android Response Model 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;
}
Interface Class 接口类别
public interface API_Service {
@Headers("content-type: application/json")
@POST("api/user/add")
Call<Response_Success> addFacebookUser(@Body UserFacebook userFacebook);}
API Call in MainActivity 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();
}
});
Debug mode in android studio; android studio中的调试模式; I get MaltFormedJsonException, but I added that exception in try catch.
我得到了MaltFormedJsonException,但是我在try catch中添加了该异常。
Your Json response 您的Json回应
{success:'yes'}
{成功:'是'}
is invalid. 是无效的。 The key and (string) value must be in double quotes.
键和(字符串)值必须用双引号引起来。
Either make sure your response is in double quotes: 请确保您的回复用双引号引起来:
{"success":"yes"}
{“成功”:“是”}
or try this instead: 或尝试以下方法:
$response = array();
$response["success"] = "yes";
echo json_encode($response);
Note: you can check to see if any JSON string is valid at: https://jsonlint.com/ Or https://jsonformatter.curiousconcept.com/ 注意:您可以在以下网址查看任何JSON字符串是否有效: https : //jsonlint.com/或https://jsonformatter.curiousconcept.com/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.