JSON.parse()javascript意外的令牌{

时间:2016-06-19 18:24:05

标签: java json

我收到以下错误:

undefined:2
{"data":{"my":88.43869018554688,"mx":-293.594970703125},"id":2}
^
SyntaxError: Unexpected token {
    at Object.parse (native)
    at Socket.<anonymous>(/home/lchost/fishy.io/server/custom_modules/game.js:34:23)

我在服务器上的代码:

socket.on('data', function(data) {
    console.log(data.toString());
    var json = JSON.parse(data.toString());
    ...
Android客户端上的

代码:

public class TouchEventObject implements JSONable {

public float mx;
public float my;

public TouchEventObject(float mx, float my) {
    this.mx = mx;
    this.my = my;
}

@Override
public JSONObject toJSON() {
    JSONObject json = new JSONObject();
    try {
        json.put("mx", mx);
        json.put("my", my);
    } catch(Exception e) {};
    return json;
}
}

@Override
public boolean onTouchEvent(MotionEvent event) {

    if(world != null && me != null && canvas_width != -1 && canvas_height != -1) {
        Camera camera = Camera.getInstance();
        float x = camera.getX() <= 0 ? event.getX() - me.x*camera.getScale() : camera.getX() >= world.WIDTH - canvas_width ? ((world.WIDTH - canvas_width) + event.getX()) - me.x*camera.getScale() : event.getX() - canvas_width/2;
        float y = camera.getY() <= 0 ? event.getY() - me.y*camera.getScale() : camera.getY() >= world.HEIGHT - canvas_height ? ((world.HEIGHT - canvas_height) + event.getY()) - me.y*camera.getScale() : event.getY() - canvas_height/2;

        if (client != null && client.isConnected()) {
            JSONObject json = new TouchEventObject(x, y).toJSON();
            client.sendMessage(PacketType.MOUSEMOVE, json);
        }
    }

    return true;
}

任何可能导致问题的想法??? 这真的很奇怪,因为有几次这不会引发错误但是在3或4次成功处理套接字传输之后它确实会失败。 提前谢谢你

1 个答案:

答案 0 :(得分:0)

其实@Mr。骆驼是对的。我的代码只在一条消息中发送了两个JSON ...我已将Thread.sleep(100)放入处理触摸事件的代码中:

@Override
public boolean onTouchEvent(MotionEvent event) {

    if(world != null && me != null && canvas_width != -1 && canvas_height != -1) {
        Camera camera = Camera.getInstance();
        float x = camera.getX() <= 0 ? event.getX() - me.x*camera.getScale() : camera.getX() >= world.WIDTH - canvas_width ? ((world.WIDTH - canvas_width) + event.getX()) - me.x*camera.getScale() : event.getX() - canvas_width/2;
        float y = camera.getY() <= 0 ? event.getY() - me.y*camera.getScale() : camera.getY() >= world.HEIGHT - canvas_height ? ((world.HEIGHT - canvas_height) + event.getY()) - me.y*camera.getScale() : event.getY() - canvas_height/2;

        if (client != null && client.isConnected()) {
            JSONObject json = new TouchEventObject(x, y).toJSON();
            client.sendMessage(PacketType.MOUSEMOVE, json);
            try {
                Thread.sleep(100);
            } catch(Exception e) {}
        }
    }

    return true;
}