【问题标题】:Spring boot websocket send jsonstringSpring Boot websocket 发送 jsonstring
【发布时间】:2018-12-26 15:27:02
【问题描述】:

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

RMModel.java

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

@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 客户端

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

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

【问题讨论】:

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

标签: java spring-boot stomp spring-websocket


【解决方案1】:

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

RMModel.java

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 对象)。
猜你喜欢
  • 2018-12-31
  • 2018-09-19
  • 2016-06-07
  • 1970-01-01
  • 2016-05-06
  • 2020-06-17
  • 2015-07-24
  • 2018-02-21
  • 1970-01-01
相关资源
最近更新 更多