简体   繁体   中英

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

I am using Spring MVC for creating a restful API. I have two different API endpoints where I need to serialise same POJO in two different ways. I have illustrated the same below:

Course API

url - /course/{id}

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

My Course Pojo is in accordance with the above structure, so the default serialisation works.

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
}

Now, for another Students API

url - /student/{id}

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

And my Student class looks like this:

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

    //getters and setters follow
}

Please note that there is no institute property in Student class because institute can be transitively determined from the course.getInstitute getter. But that ends up in a serialisation structure similar to course API. How can I use a custom serialisation only for the Students API without modifying the POJO Structure.

There are a N number of solutions to this that come to my mind, which is the most elegant and preferred one, I would like to know.

I guess this is the most elegant thing I sorted out which works for me.

So, here is my class 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();
    }
}

This way I am exposing a Java bean property institute through a getter while not holding a reference to it in my Student Object.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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