将子类序列化为子元素

时间:2013-07-02 13:24:00

标签: json serialization jackson

我正在使用Jackson并希望将子类'字段序列化为子元素。不幸的是杰克逊有糟糕的文件。

@JsonRootName(value = "subclass")
public class ProfilerTask extends Task {

    private int age;

    private int grade;



    public ProfilerTask(String name, Date createdOn, int age, int grade) {
        super(name, createdOn);
        this.age = age;
        this.grade = grade;
    }

    /**
     * @return the age
     */
    public int getAge() {
        return age;
    }

    /**
     * @return the grade
     */
    public int getGrade() {
        return grade;
    }

}

我得到了这个:{"name":"test task","createdOn":1372771395040,"age":25,"grade":4},而我实际上希望子类的字段是一个子元素。

1 个答案:

答案 0 :(得分:1)

我认为,你应该考虑构成而不是继承。但是如果你真的想要继承,你必须改变POJO类。您可以创建新的内部类,并将所有属性和字段移动到此新类中。看我的例子:

public class ProfilerTask extends Task {

    private Subclass subclass;

    public ProfilerTask(String name, long createdOn, int age, int grade) {
        super(name, createdOn);
        this.subclass = new Subclass();
        this.subclass.age = age;
        this.subclass.grade = grade;
    }

    public Subclass getSubclass() {
        return subclass;
    }

    @JsonIgnore
    public int getAge() {
        return subclass.age;
    }

    @JsonIgnore
    public int getGrade() {
        return subclass.grade;
    }

    public class Subclass {
        private int age;
        private int grade;

        public int getAge() {
            return age;
        }

        public void setAge(int age) {
            this.age = age;
        }

        public int getGrade() {
            return grade;
        }

        public void setGrade(int grade) {
            this.grade = grade;
        }
    }
}

现在,请看我简单的主要方法:

ObjectMapper mapper = new ObjectMapper();
ProfilerTask task = new ProfilerTask("test task", 1372771395040L, 25, 4);

System.out.println(mapper.writeValueAsString(task));

此程序打印:

{"name":"test task","createdOn":1372771395040,"subclass":{"age":25,"grade":4}}

我认为这是使用Jackson在JSON中创建子元素的最简单方法。