java - 如何从登录API改造成功的字符串格式获取数据?

标签 java android retrofit2

请阅读我在几个小时前提出的这个问题: How is it possible that POST API working in Postman but not the retrofit?

实际上,从 Retrofit 响应中,我从 ResponseBody 对象中获取了字符串格式的响应。

解释:我的状态码是200,成功,但是从响应正文来看,它只是字符串。如何从该字符串中获取所有数据?

登录成功后,我在 onResponse 中收到 String。我已经将用户凭据发送到此 APi,并且在 API 响应中,我收到了此字符串。

可能有一些与base64关系的编码解码。

最佳答案

public class LoginModel {

    @SerializedName("body")
    private Body body;

    public Body getBody() {
        return body;
    }

    public static class Body {
        @SerializedName("userPwd")
        private String userpwd;
        @SerializedName("prodId")
        private int prodid;
        @SerializedName("emailId")
        private String emailid;
        @SerializedName("customerId")
        private int customerid;

        public String getUserpwd() {
            return userpwd;
        }

        public int getProdid() {
            return prodid;
        }

        public String getEmailid() {
            return emailid;
        }

        public int getCustomerid() {
            return customerid;
        }
    }
}

现在,如果您关注了 this answerretrofit界面是这样的

@Headers("Content-Type: application/json")
@POST("login/desktop/user")
Call<ResponseBody> getToken(@Body HashMap<String, HashMap<String, Object>> data);

修改为

@Headers("Content-Type: application/json")
@POST("login/desktop/user")
Call<LoginModel> getToken(@Body HashMap<String, HashMap<String, Object>> data); // change here

现在您可以在 onResponse() 中获取数据像这样

LoginModel loginData = response.body();

String pswd = loginData.getBody().getUserpwd();

PS = 如果您可以更改响应,我建议您更改 var body从对诸如 data 之类的其他内容的回复.

SerializedName用于POJO类(class)并不重要,read more about them here

希望这会有所帮助!

关于java - 如何从登录API改造成功的字符串格式获取数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60338238/

相关文章:

java - 在 Android Studio 中连接到数据库的基本 URL

java - Java 注释是否添加符号或功能?

java - JFrame : setDefaultCloseOperation has no effect

android - 如何制作启动画面并在后台运行 ListView 进程?

java - 如何将数据从线程发送到主要 Activity java android

java - 如何从 Retrofit2 获得字符串响应?

JAVA:类不会序列化

java - SQLException 是否发生取决于我们检索的值

android - 如何在 Android 中使用 woocommerce Api 改造实现 OAuth 1.0a

android - 使用 Retrofit 在 URL 中获取带有 `&` 附加参数的请求