【问题标题】:How to convert POJO object to json string using gson for a specified field?如何使用指定字段的 gson 将 POJO 对象转换为 json 字符串?
【发布时间】:2019-06-26 12:59:50
【问题描述】:

我正在使用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();

            }
        });
    }

【问题讨论】:

    标签: android json gson retrofit2


    【解决方案1】:

    从构造函数中删除这段代码:

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

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

    祝你好运!

    【讨论】:

    • 感谢您的回答。保留空构造函数解决了我的问题。
    【解决方案2】:

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

    JSONObject data =new JSONObject();
    data.put("email", email@email.com)
    

    将数据对象发送到改造。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-04
      • 2018-11-16
      • 2013-05-19
      • 1970-01-01
      • 2017-01-24
      • 1970-01-01
      相关资源
      最近更新 更多