繁体   English   中英

如何在Spring MVC中使用两个不同的自定义序列化程序为两个不同的API序列化POJO?

[英]How to serialise a POJO with two different custom serialisers for two different apis in Spring MVC?

我正在使用Spring MVC创建一个宁静的API。 我有两个不同的API端点,需要以两种不同的方式序列化相同的POJO。 我已经在下面说明了相同的内容:

课程API

url - /course/{id}

response - {
    "id": "c1234",
    "name": "some-course",
    "institute": {
        "id": "i1234",
        "name": "XYZ College"
    }
}

我的Course Pojo符合上述结构,因此默认序列化有效。

class Course {
    private String id;
    private String name;
    private Institute institute;

    //getters and setters follow
}

class Institute {
    private String id;
    private String name;

    //getters and setters follow
}

现在,对于另一个Students API

url - /student/{id}

response - {
    "id":"s1234",
    "name":"Jon Doe",
    "institute": {
        "id": "i1234",
        "name": "XYZ college"
    },
    "course": {
        "id": "c1234",
        "name": "some-course"
    }
}

我的Student班级看起来像这样:

class Student {
    private String id;
    private String name;
    private Course course;

    //getters and setters follow
}

请注意, Student班级没有institute财产,因为可以通过course.getInstitute getter传递地确定course.getInstitute 但这最终导致了类似于课程API的序列化结构。 如何在不修改POJO结构的情况下仅对学生API使用自定义序列化。

我想知道有N种解决方案,这是我想知道的最优雅,最喜欢的解决方案。

我想这是我挑选出的最优雅的东西,对我有用。

所以,这是我班的Student

class Student {

    private String id;
    private String name;

    @JsonIgnoreProperties({"institute"})
    private Course course;

    //getters and setters

    //Adding one more getter
    public Institute getInstitute() {
        return this.course.getInstitute();
    }
}

这样,我通过getter公开了Java Bean属性institute ,而没有在我的Student Object中保留对它的引用。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM