如何使用GSON将POJO对象转换为JSON字符串



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

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

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

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

祝你好运!

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

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

将数据对象发送到改装。

最新更新