关于java:Spring boot websocket发送jsonstring

Spring boot websocket send jsonstring

我是 Spring Boot 新手,我正在尝试使用 websocket 发回 jsonstring,但我认为它返回的 jsonstring 格式不正确。

RMModel.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public class RMModel {
    private Integer inQueue;
    private Integer suspended;

    public RMModel getMessage() {
        this.inQueue = new Random().nextInt(11);
        this.suspended = new Random().nextInt(11);
        return this;
    }

    @Override
    public String toString() {
        return"{" +""inqueue":" + this.inQueue +"," +""suspended":" + this.suspended + '}';
    }
}

WebSocketScheduler.java

1
2
3
4
5
6
7
8
9
10
11
12
@Component
public class WebSocketScheduler {

    @Autowired
    private SimpMessagingTemplate template;

    @Scheduled(fixedRate = 1000)
    public void publishData() {
        String data = RMModel.getData().toString();
        this.template.convertAndSend("/topic/recon", data);
    }
}

所以我想将 RMModel 的 jsonstring 返回给客户端。我有 angular2 客户端

1
this._stompService.subscribe('/topic/recon').subscribe(res => console.log(JSON.parse(res.body)));

它没有转换为 json 对象。
在spring boot中返回jsonstring的正确方法是什么?

相关讨论

  • 你有什么错误吗?无论如何,让 toString 来构建 json 对象真的很可疑。如果您将 RMModel 传递给 convertAndSend,在后台,它将按照您的预期将其转换为 json 字符串(它使用 jackson 来完成此操作)
  • 我也是这么想的。但是客户端除了字符串对象之外什么都没有收到......我不知道为什么
  • 尝试直接发送 RMModel 而不是像字符串一样发送它,看看它是否仍然是问题。我只有一个我测试过的工作angular 1.x,它运行良好。也许 angular 2 是另一种野兽 xD
  • 我试过了,服务器端没有错误,但客户端没有收到任何东西......

问题解决了。
模型不应该有返回自身的方法,jackson 会抛出异常。

RMModel.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
public class RMModel {
    private Integer inQueue;
    private Integer suspended;

    public Integer getInQueue() {
        return inQueue;
    }

    public void setInQueue(Integer maximum) {
        this.inQueue = new Random().nextInt(maximum);
    }

    public Integer getSuspended() {
        return suspended;
    }

    public void setSuspended(Integer maximum) {
        this.suspended = new Random().nextInt(maximum);
    }

    @Override
    public String toString() {
        return"{" +""inqueue":" + this.inQueue +"," +""suspended":" + this.suspended + '}';
    }

相关讨论

  • 我猜内容类型将是 text/plain 而不是 application/json。在我的情况下,如果我尝试手动设置消息的内容类型,那么 JSON 会被转义(因此它实际上是 JSON 字符串而不是 JSON 对象)。

以上是关于java:Spring boot websocket发送jsonstring的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>