android - 如何使用 Retrofit 查看创建的 JSON 字符串

标签 android json gson retrofit

我不确定这是否是一个愚蠢的问题(因此我找不到答案)但我想知道是否可以 Toast 或 Log 输出正在发送到服务器的创建的 JSON,当它已发送。

我只是想看看创建的 JSON - 我正在使用以下方法,它使用 Retrofit.addConverterFactory(GsonConverterFactory.create(gson)):

private void addTeamMember(final List teamMemberArray,final String team_id) {

    //helps with debugging regarding post requests
    Gson gson = new GsonBuilder()
            .setLenient()
            .create();


    //Retrofit is a REST Client for Android and Java by Square.
    //It makes it relatively easy to retrieve and upload JSON (or other structured data) via a REST based webservice
    Retrofit retrofit = new Retrofit.Builder()
            //directing to the localhost which is defined in the Constants Class as BASE_URL
            .baseUrl(Constants.BASE_URL)
            //Add converter factory for serialization and deserialization of objects.
            //Gson passed as a parameter to help with debug
            .addConverterFactory(GsonConverterFactory.create(gson))
            //Create the Retrofit instance using the configured values.
            .build();



    //The Retrofit class generates an implementation of the RequestInterface interface.
    RequestInterface requestInterface = retrofit.create(RequestInterface.class);



    for (Object x : teamMemberArray) {


        //create new Team object
        TeamMember teamMember = new TeamMember();


        //setter
        teamMember.setFullName(String.valueOf(x));
        teamMember.setTeam_id(team_id);

        Toast.makeText(getActivity(), teamMember.getFullName(),
                Toast.LENGTH_LONG).show();


        //create new server object
        final ServerRequest request = new ServerRequest();


        //make a request to set the operation to Team_Member
        request.setOperation(Constants.Team_Member);
        //set values entered for the new teamMember to be sent to the server
        request.setTeamMember(teamMember);


        Call<ServerResponse> response = requestInterface.operation(request);


        /**
         * Enqueue is used to Asynchronously send the request and notify callback of its response or if an error occurred
         * talking to the server, creating the request, or processing the response.
         */


        response.enqueue(new Callback<ServerResponse>() {

            @Override
            public void onResponse(Call<ServerResponse> call, retrofit2.Response<ServerResponse> response) {

                ServerResponse resp = response.body();


            /*Snackbars provide lightweight feedback about an operation. They show a brief message at the
            bottom of the screen on mobile and lower left on larger devices. Snackbars appear above all other
            elements on screen and only one can be displayed at a time.
             */


                Snackbar.make(getView(), resp.getMessage(), Snackbar.LENGTH_LONG).show();


                if (resp.getResult().equals(Constants.SUCCESS)) {
                    SharedPreferences.Editor editor = pref.edit();


                    Log.d("TEST VALUE", "getTeamMemberName() = " + response.body().getTeamMember().getFullName() );
                    Log.d("TEST VALUE", "getTeamMemberUniqueID() = " + response.body().getTeamMember().getUnique_id());
                    Log.d("TEST VALUE", "getTeamMemberTeamID() = " + response.body().getTeamMember().getTeamID());

                          editor.putString(Constants.FULL_NAME, resp.getTeamMember().getFullName());
                          editor.putString(Constants.UNIQUE_ID, resp.getTeamMember().getUnique_id());
                          editor.putString(Constants.TEAM_ID, resp.getTeamMember().getTeamID());
                          editor.apply();
                          goToQuestions();

                }

                progress.setVisibility(View.INVISIBLE);

            }

            @Override
            public void onFailure(Call<ServerResponse> call, Throwable t) {

                progress.setVisibility(View.INVISIBLE);
                Log.d(Constants.TAG, "failed" + t);
                Snackbar.make(getView(), t.getLocalizedMessage(), Snackbar.LENGTH_LONG).show();


            }
        });
    }

}

我的理由是,如果我能看到正在发送的 JSON,它将帮助我在使用 Postman 时进行调试。

最佳答案

您可以使用 OkHttpInterceptor 通过 Retrofit 记录网络调用。它将拦截任何调用并在记录器中显示日志。

在你的gradle中添加依赖:

 compile 'com.squareup.okhttp3:logging-interceptor:3.8.0'

然后在设置改造客户端之前使用:

HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
logging.setLevel(Level.BASIC);
OkHttpClient client = new OkHttpClient.Builder()
  .addInterceptor(logging)
  .build();

最后添加改造:

 retrofit = new Retrofit.Builder()
                .baseUrl(BASE_URL)
                .client(client)
                .addConverterFactory(GsonConverterFactory.create())
                .build();

关于android - 如何使用 Retrofit 查看创建的 JSON 字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45635889/

相关文章:

java - 如何用数组的数组解析json数组

android - Retrofit 响应解析建议

java - Gson 和 CSV 冲突?

java - 新手 Android NullPointerException 故障排除

java - NsdManager 不解析多个发现的服务

android - java.text.ParseException : Unparseable date: Mon Apr 08 00:00:00 IST 2013 异常

java - 将对象序列化为 Json 时出现 NullPointerException

android - Gradle Kotlin DSL 中 Dynatrace 的配置

javascript - HTML/Javascript 表单 如何将表单数据序列化为 JSON 并显示在类中?

json - 为什么 ReSTLet 无法注册 JSON 转换器?