是否可以在 @OnMessage 函数中使用 POJO 而不是 String?

Is it possible to use a POJO instead of a String in a @OnMessage function?

基本上,我可以使用:

@OnMessage
public void handleMessage(Message message, Session session) {

而不是:

@OnMessage
public void handleMessage(String message, Session session) {

消息 class 看起来像:

public class Message {
    private String action;
    private String value;
}

按照文档,是不可能的:

The allowed parameters are:

Exactly one of any of the following choices
    if the method is handling text messages:
        String to receive the whole message
        Java primitive or class equivalent to receive the whole message converted to that type
        String and boolean pair to receive the message in parts
        Reader to receive the whole message as a blocking stream
        any object parameter for which the endpoint has a text decoder (Decoder.Text or Decoder.TextStream).
    if the method is handling binary messages:
        byte[] or ByteBuffer to receive the whole message
        byte[] and boolean pair, or ByteBuffer and boolean pair to receive the message in parts
        InputStream to receive the whole message as a blocking stream
        any object parameter for which the endpoint has a binary decoder (Decoder.Binary or Decoder.BinaryStream).
    if the method is handling pong messages:
        PongMessage for handling pong messages
and Zero to n String or Java primitive parameters annotated with the PathParam annotation for server endpoints.
and an optional Session parameter

https://docs.oracle.com/javaee/7/api/javax/websocket/OnMessage.html

但如果您使用 JAXRS(与 RESTEasy、Jersey 或 CXF),您将能够使用 Json 提供程序(Jackson、Gson)直接在目标对象中解析。