我是 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 的正确方法是什么?
最佳答案
问题已解决。 该模型不应该有返回自身的方法,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 + '}';
}
关于java - Spring boot websocket发送jsonstring,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51406591/