微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

如何解决是否可以在@OnMessage 函数中使用 POJO 而不是字符串?

基本上,我可以使用:

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

代替:

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

消息类看起来像:

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

解决方法

按照文档,这是不可能的:

允许的参数是:

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 Provider(Jackson、Gson)直接在目标对象中进行解析。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。