如何使用java和gson中的构建器模式将select类字段序列化为json字符串?

alen0pnh  于 2021-08-20  发布在  Java
关注(0)|答案(1)|浏览(348)

我创建了一个带有生成器模式的用户类,目的是将其序列化为一个json字符串,以便发布。现在,需求已经改变,我需要能够修补现有记录,更新记录集中的一个或多个字段,但不是所有字段。下面的示例在其用户类中有5个字段,但是想象一下,如果它有30个甚至40个字段,包括int类型。

import com.google.gson.*;

class User 
{
    //All final attributes
    private final String firstName;
    private final String lastName;
    private final int age;
    private final String phone;
    private final String address;

    private User(UserBuilder builder) {
        this.firstName = builder.firstName;
        this.lastName = builder.lastName;
        this.age = builder.age;
        this.phone = builder.phone;
        this.address = builder.address;
    }

    //All getter, and NO setter to provide immutability
    public String getFirstName() {
        return firstName;
    }
    public String getLastName() {
        return lastName;
    }
    public int getAge() {
        return age;
    }
    public String getPhone() {
        return phone;
    }
    public String getAddress() {
        return address;
    }

    public static class UserBuilder 
    {
        private String firstName;
        private String lastName;
        private int age;
        private String phone;
        private String address;

        public UserBuilder() {
        }

        public UserBuilder(String firstName, String lastName) {
            this.firstName = firstName;
            this.lastName = lastName;
        }

        public UserBuilder firstName(String firstName) {
            this.firstName = firstName;
            return this;
        }

        public UserBuilder lastName(String lastName) {
            this.firstName = lastName;
            return this;
        }
        public UserBuilder age(int age) {
            this.age = age;
            return this;
        }
        public UserBuilder phone(String phone) {
            this.phone = phone;
            return this;
        }
        public UserBuilder address(String address) {
            this.address = address;
            return this;
        }
        //Return the finally consrcuted User object
        public User build() {
            User user =  new User(this);
            return user;
        }
    }
}

public class TestUserBuild {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        User user = new User.UserBuilder().
        //No last name
        //No age
        //No phone
        //no address
        .firstName("Super")
        .build();

        System.out.println(user); // User: Super, null, 0, null, null

        Gson gson = new Gson();

        System.out.println(gson.toJson(user)); // {"firstName":"Super","age":0}
    }
}

我没有指定年龄,但它在json字符串中。我认为构建器模式将有助于创建任意数量的json字符串排列,即更新名字和姓氏、仅更新名字、仅更新年龄、仅更新姓氏和电话号码等。。。
对于这个问题,生成器模式方法不是正确的解决方案吗?如果这是一个可接受的解决方案,我如何利用构建器模式将用户类序列化为json字符串,但只使用我选择的字段?在gson库中是否有我可以利用的东西来实现这个任务,比如创建自定义类型适配器?也许我可以创建一个自定义类型适配器,它将所有字段作为输入,检查每个字段是否为null,或者是否为0表示整数,然后只使用delta构建json字符串。

7kjnsjlb

7kjnsjlb1#

您的“年龄”字段值为0,因为“int”有一个默认值。如果希望年龄字段默认为空,请使用“整数”。
构建器模式的一些优点是不可变的(您可以选择只允许构建器在创建时修改类,从类中删除所有setter),并且对于示例化具有多个属性的类更简洁。
但您不需要保持构建器模式不变。如果我正确理解您的需求,您可以在对象创建过程中保持生成器模式的多功能性,并保持类上的setter能够轻松地更新字段。

import com.google.gson.*;

class User {
//Your attributes don't need to be final
private String firstName;
private String lastName;
private int age;
private String phone;
private String address;

private User(UserBuilder builder) {
    this.firstName = builder.firstName;
    this.lastName = builder.lastName;
    this.age = builder.age;
    this.phone = builder.phone;
    this.address = builder.address;
}

//getters AND setters (omitted for brevity)

//builder class stays as is, omitted for brevity

public class TestUserBuild {

    public static void main(String[] args) {
        User user = new User.UserBuilder()
        .firstName("Super")
        .build();

        //when you need to update
        user.setAge(42);
    }
}

问题是,如果需要定期更新字段,为什么需要不变性?您是否应该完全删除不变性约束(通过在类中保留setter)?您是否需要能够根据特定的业务规则更新特定的字段组合?如果后者是真的,我建议不要使用贫血模型(一个“getter和setter包”),而是添加特定于领域的方法来更新相关字段。您的用户类将如下所示:

class User {
    //Your attributes don't need to be final
    private String firstName;
    private String lastName;
    private int age;
    private String phone;
    private String address;

    private User(UserBuilder builder) {
        this.firstName = builder.firstName;
        this.lastName = builder.lastName;
        this.age = builder.age;
        this.phone = builder.phone;
        this.address = builder.address;
    }
    //getters ONLY (omitted for brevity)
    //no setters, only domain-relevant methods which update fields as needed
    public void setIdentity(String firstName, String lastName) {
        this.firstName = firstName;
        this.lastName = lastName;
    }
    public void setCoordinates(String phone, String address) {
        this.phone = phone;
        this.address = address;
    }
}
//builder class stays as is

public class TestUserBuild {

    public static void main(String[] args) {
        User user = new User.UserBuilder()
        .firstName("Super")
        .build();

        //update identity (say, your frontend has an "identity" page with only firstName and lastName on it
        user.setIdentity("Chris", "Neve");
        //your frontend page allowing user to update coordinates
        user.setCoordinates("+331231231", "7th av, NYC");
    }
}

相关问题