簡體   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