如何使用gson为指定字段将POJO对象转换为json字符串?

时间:2019-06-26 12:59:50

标签: android json gson retrofit2

我正在使用Retrofit2进行密码恢复,API请求通过用户输入的电子邮件地址发送到服务器。 我只在POJO中设置电子邮件,转换后,JSON字符串如下所示:

{"email":"email@email.com", "password":"", "password_confirmation":"", "token":""}

但是我需要发送的JSON应该如下所示:

{"email":"email@email.com"}

如果我要创建另一个具有电子邮件参数的POJO类,那么我将获得所需的字符串,但是我只是想知道是否可以使用当前的POJO。

如何使用gson为指定字段将POJO对象转换为JSON字符串?

请参考以下代码:

   public class User {

    private String email;
    private String password;
    private String password_confirmation;
    private String token;

    public User() {
       this.email="";
       this.password="";
       this.password_confirmation="";
       this.token="";
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getPassword() {
        return password;
    }

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

    public String getPassword_confirmation() {
        return password_confirmation;
    }

    public void setPassword_confirmation(String password_confirmation) {
        this.password_confirmation = password_confirmation;
    }

    public String getToken() {
        return token;
    }

    public void setToken(String token) {
        this.token = token;
    }
}

我的Api界面

public interface Api{

  @POST("/api/password/create")
  @Headers({"Accept:application/json", "Content-Type:application/json"})
  Call<User> Create(@Body RequestBody requestBody); 

}

我的改造方法

 private void authenticateEmail(final Context context) {

        User user=new User();
        Api api=new Api();

        String email = edt_forgot_email.getText().toString().trim();

       Gson gson = new GsonBuilder()
                    .setDateFormat(SERVICE_DATE_FORMAT)
                    .setLenient()
                    .create();
        api = new Retrofit.Builder()
                    .baseUrl(BASE_URL)
                    .addConverterFactory(GsonConverterFactory.create(gson))
                    .build();

        user.setEmail(email);
        Gson lGson = new GsonBuilder().setDateFormat(SERVICE_DATE_FORMAT).create();
        String jsonString =  lGson.toJson(user);
        Log.d("debug", "jsonString==>" + jsonString);


        final RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), jsonString);
        Call<User> call = api.Create(requestBody);
        Log.d("debug", "url: " + call.request().url().toString());

        call.enqueue(new Callback<User>() {
            @Override
            public void onResponse(@NonNull Call<User> call, @NonNull Response<User> response) {
                Log.d("debug", "responsecode==>" + response.code());
                Log.d("debug", "responsebody==>" + response.body());

                if (response.code() == 200) {

                   String msg = "We have emailed you OTP";
                  Toast.makeText(activity, msg, Toast.LENGTH_SHORT).show();

                } 
            }

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

               Toast.makeText(activity, "server error",Toast.LENGTH_SHORT).show();

            }
        });
    }

2 个答案:

答案 0 :(得分:0)

从构造函数中删除此代码:

public User() {
    this.email="";
    this.password="";
    this.password_confirmation="";
    this.token="";
}

如果要从输出json中排除空值,则应将其设置为null。

祝你好运!

答案 1 :(得分:0)

您可以像这样为单个字段创建JSON对象:

Field B

发送数据对象进行改造。