简体   繁体   中英

Spring Jackson serialization by interface

I have two interfaces and one class:

@JsonDeserialize(as = UserEvent.class)
@JsonSerialize(as = EventAttendee.class)
public interface EventAttendee {

    Long getId();
    void setId(Long id);

    User getUser();
    void setUser(User user);

    UserResponse getUserResponse();
    void setUserResponse(UserResponse userResponse);

}

@JsonDeserialize(as = UserEvent.class)
@JsonSerialize(as = UserAttendee.class)
public interface UserAttendee {

    Long getId();
    void setId(Long id);

    Event getEvent();
    void setEvent(Event user);

    UserResponse getUserResponse();
    void setUserResponse(UserResponse userResponse);
}

public class UserEvent extends BaseEntity implements EventAttendee, UserAttendee  {

    private Event event = new Event();
    private User user = new User();
    private UserResponse userResponse;

}

I want return different values of UserEvent based on interface I returning from my controller. Like this:

public List<EventAttendee> getEventAttendees(@PathVariable Long eventId) {

}

public List<UserAttendee> getUserEvents(@PathVariable Long userId) {

}

But it taking first implemented interface(in my case EventAttendee) and return it type from BOTH controlers.

How can I return EventAttendee values from one controller, and UserAttendee from another?

Ok, after I posted question I found answer...

I used Views instead of interfaces. There still interfaces in class, but it's serve for other needs now (not for Jackson).

public class Views {
    public interface UserResponse {}
    public interface Event extends UserResponse {}
    public interface User extends UserResponse {}
}

public class UserEvent extends BaseEntity implements EventAttendee, UserAttendee {

    @JsonView(Views.User.class)
    private Event event = new Event();

    @JsonView(Views.Event.class)
    private User user = new User();

    @JsonView(Views.UserResponse.class)
    private UserResponse userResponse;
}

@JsonView(Views.Event.class)
public List<EventAttendee> getEventAttendees(@PathVariable Long eventId) {

}

@JsonView(Views.User.class)
public List<UserAttendee> getUserEvents(@PathVariable Long userId) {

}

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