/json-view-websocket-demo

This demo shows the use of Jackson JSON Views with Spring's WebSocket Support.

Primary LanguageJava

Jackson JSON Views with Spring’s WebSocket Support

This demo shows the use of Jackson JSON Views with Spring’s WebSocket Support.

Read about Jackson JSON Views

Jackson JSON View

public class Views {

    public static class Public {
    }

    public static class Internal extends Public {
    }
}

Model

public class Item {

    @JsonView(Views.Public.class)
    private Integer id;

    @JsonView(Views.Public.class)
    private String itemName;

    @JsonView(Views.Internal.class)
    private String ownerName;

    ...
}

Controller

Use the CONVERSION_HINT_HEADER with SimpMessagingTemplate.

@MessageMapping("/messaging-template")
public void useMessagingTemplate(Principal principal) {
    var user = principal.getName();
    var destination = "/response";
    var item = getItem();
    var headers = getHeaders();

    messagingTemplate.convertAndSendToUser(user, destination, item, headers);
}

private Map<String, Object> getHeaders() {
    return Map.of(CONVERSION_HINT_HEADER, Views.Public.class);
}

Use the @JsonView annotation for controller methods.

@MessageMapping("/send-to-user-annotation")
@SendToUser(value = "/response", broadcast = false)
@JsonView(Views.Public.class)
public Item useSendToUserAnnotation() {
    return getItem();
}