首页 > 解决方案 > 从 JSON 响应改造中获取字符串数据

问题描述

我正在使用可以从服务器获取的 JSON 响应,一开始我必须在我的应用程序中登录,所以我使用这样的 api:

@Headers("Content-type: application/json")
    @POST("/v1/login")
    Call<Post> auth(@Body Post body);

还有我的 POJO 类:

public class Post {
    @SerializedName("username")
    private String username;
    @SerializedName("password")
    private String password;

    public Post(String username, String password) {
        this.username = username;
        this.password = password;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername (String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }
}

毕竟在我的 mainactivity 类中初始化它:

public void sendPost() {
        final EditText titleEt = findViewById(R.id.login);
        final EditText bodyEt = findViewById(R.id.password);
        final String a = titleEt.getText().toString().trim();
        final String b = bodyEt.getText().toString().trim();

        HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
        interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
        OkHttpClient client = new OkHttpClient.Builder().addInterceptor(interceptor).build();
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl("https://server/")
                .client(client)
                .addConverterFactory(GsonConverterFactory.create())
                .build();

        APIService mAPIService = retrofit.create(APIService.class);
        //retrofit.create(APIService.class);

        mAPIService.auth(new Post(a, b)).enqueue(new Callback<Post>() {
            @Override
            public void onResponse(@NonNull Call<Post> call, @NonNull Response<Post> response) {
                if (response.isSuccessful()) {
                    Toast.makeText(LoginActivity.this, "Post submitted to API.", Toast.LENGTH_LONG).show();
                    Intent intent = new Intent(LoginActivity.this, SecondScreen.class);
                    findViewById(R.id.btn_submit).getBackground().setColorFilter(Color.parseColor("#1cd000"), PorterDuff.Mode.MULTIPLY);
                    startActivity(intent);
                    saveData();
                   /* try {
                        String responseString = String.valueOf(response.body());
                        TextView txt = findViewById(R.id.post);
                        txt.setText(responseString);
                    }
                    catch (Exception e){
                        e.printStackTrace();
                    }*/


                } else {
                    Toast.makeText(LoginActivity.this, "Unable to submit post to API.Error!!!", Toast.LENGTH_LONG).show();
                    findViewById(R.id.btn_submit).getBackground().setColorFilter(Color.parseColor("#FF0000"), PorterDuff.Mode.MULTIPLY);
                }
            }

            @Override
            public void onFailure(@NonNull Call<Post> call, @NonNull Throwable t) {
                Toast.makeText(LoginActivity.this, "Unable to submit post to API.", Toast.LENGTH_LONG).show();

            }
        });
    }

如您所见,我评论说我试图从 JSON 响应中获取一些数据,一般来说,我想从响应中获取我的访问令牌,如果可能的话,我也不想创建一些用于获取的类,因为我已经在我的 MainActivity 类中初始化了我的改造。登录后,我也可以在 JSON 中接收和发送消息,但我想将此数据插入到简单的列表视图中。所以我希望这个论坛的人能帮助我解决我的问题。对不起我的英语可能不好。

标签: androidretrofit2

解决方案


您必须了解每个 Retrofit 请求都是异步的,这意味着它最终会在您的应用程序运行时执行。你应该使用RxJava来帮助你,因为你应该使用来观察你需要从你的API获取的数据。

重要说明:由于未在主线程中运行,更新响应中的 UI 也可能会触发异常。

一些有用的链接来实现你所需要的:

https://www.toptal.com/android/functional-reactive-android-rxjava

https://www.journaldev.com/20433/android-rxjava-retrofit

https://medium.com/3xplore/handling-api-calls-using-retrofit-2-and-rxjava-2-1871c891b6ae


推荐阅读