在序列化中排除枚举

时间:2018-01-08 11:14:15

标签: android gson

我使用Gson将类转换为Json。我不想在我转换的Java对象中映射枚举类。哪个是要排除它的注释?

在课程和个人成员上尝试了@Exclude

1 个答案:

答案 0 :(得分:0)

根据doc,检查@Expose注释。您可以使用此批注来保留要序列化的字段。

例如,一个人实体,我不想将id序列化为json。

public class Person {

    private long id;

    @Expose
    private String name;

    @Expose
    private String intro;

    public Person(long id, String name, String intro) {
        this.id = id;
        this.name = name;
        this.intro = intro;
    }

    public long getId() {
        return id;
    }

    public void setId(long id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getIntro() {
        return intro;
    }

    public void setIntro(String intro) {
        this.intro = intro;
    }
}

然后我可以使用此代码

创建gson
public void serializeWithExpose() {
    Gson g = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();
    Person person = new Person(1L, "Name", "into");
    String s = g.toJson(person);
    System.out.println(s);
}
相关问题