1

我正在使用 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},而我实际上希望子类的字段成为子元素。

4

1 回答 1

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 中创建子元素的最简单方法。

于 2013-07-02T21:55:59.067 回答