Java到JSON转换会引发意外的令牌错误

时间:2016-03-01 04:13:13

标签: java gson

我有一个相对简单的java对象:

public class TestEvent {
    private String time;
    private String value;

    public TestEvent(){};

    public TestEvent(String time, String value)
    {
      this.time = time;
      this.value = value;
    }

    public String getTime() {
       return time;
    }

    public String setTime(String time) {
        this.time = time;
    }
}

然后我使用Spring Stomp over Websocket向客户端发送消息:

@Autowired
private SimpMessagingTemplate template;

private static Gson gson = new Gson();
private static Type type = new TypeToken<RttEvent>() {}.getType();

public void Test() {
    this.template.convertAndSend("/topic/123", gson.toJson(event, type));
}

我知道它正在客户端收到,我解析它是这样的:

var obj = JSON.parse(payload);

但我的Chrome开发人员工具控制台另有说法

<<< MESSAGE
expires:0
destination:/topic/123
subscription:sub-0
priority:4
message-id:ID\cPC78945-52231-1456805172516-3\c1\c-1\c1\c54
content-type:application/json;charset=UTF-8
timestamp:1456805443802
content-length:53

"{\"time\":\"2016-01-02\",\"value\":\"-1855286068\"}"

它抛出“Uncaught SyntaxError:unexpected token u”

1 个答案:

答案 0 :(得分:1)

看起来数据在您的回复内容中。你需要改变

var obj = JSON.parse(payload);

var obj = JSON.parse(payload.body);