简体   繁体   English

从JSON响应改造中获取字符串数据

[英]Fetch string data from JSON response retrofit

I'm working with JSON response which I can get from my server, at the beginning I have to log in at my application so I use such api: 我正在使用可以从服务器获取的JSON响应,一开始我必须登录我的应用程序,因此我使用以下api:

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

and also my POJO-class: 还有我的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;
    }
}

and after all initialize it at my mainactivity class: 并在我的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();

            }
        });
    }

as you can see I commented my trying to fetch some data from JSON response, in general, I would like to get my access token from the response and I also wouldn't like to create some classes for fetching if it is possible, because I have already initialized my retrofit at my MainActivity class. 如您所见,我评论了我试图从JSON响应中获取一些数据的评论,总的来说,我想从响应中获取访问令牌,并且如果可能的话,我也不想创建某些类来进行获取,因为我已经在MainActivity类上初始化了我的改造。 After logging in a can get my received and sent messages in JSON too, but I would like to insert this data into the simple listview. 登录后也可以使用JSON获取我的已接收和已发送消息,但是我想将此数据插入到简单的listview中。 So I hope that somebody at this forum will help me with my problem. 因此,我希望这个论坛的人能帮助我解决我的问题。 Sorry for my maybe bad English. 对不起,我英语可能不好。

You have to understand that each Retrofit request is asynchronous , that means, it will eventually be executed while your application runs. 您必须了解每个Retrofit请求都是异步的 ,这意味着最终将在您的应用程序运行时执行该请求。 You should use RxJava to help you with that, since you should use to observe the data you need to get from your API . 您应该使用RxJava来帮助您,因为您应该用来观察需要从API获取的数据。

Important Note : Also updating UI in your response from retrofit might trigger exceptions due to not running in Main Thread. 重要说明 :由于更新未在主线程中运行,因此在更新响应中更新UI可能会触发异常。

Some useful links to implement what you need : 一些有用的链接来实现您所需要的:

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

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM