2012-07-04 36 views
0

這是我在瀏覽器中得到控制檯:發送JSON在遊戲架構了一個WebSocket的創建

WS-PARSER: received {"eventPhase":2,"origin":"","bubbles":false,"defaultPrevented":false,"srcElement":{"binaryType":"blob","extensions":"","url":"ws://localhost:9000/map-socket/[email protected]","bufferedAmount":0,"readyState":1,"onerror":null,"onopen":null,"onclose":null,"protocol":"","URL":"ws://localhost:9000/map-socket/[email protected]"},"type":"message","returnValue":true,"target":{"binaryType":"blob","extensions":"","url":"ws://localhost:9000/map-socket/[email protected]","bufferedAmount":0,"readyState":1,"onerror":null,"onopen":null,"onclose":null,"protocol":"","URL":"ws://localhost:9000/map-socket/[email protected]"},"source":null,"cancelable":false,"currentTarget":{"binaryType":"blob","extensions":"","url":"ws://localhost:9000/map-socket/[email protected]","bufferedAmount":0,"readyState":1,"onerror":null,"onopen":null,"onclose":null,"protocol":"","URL":"ws://localhost:9000/map-socket/[email protected]"},"ports":[],"timeStamp":1341430631884,"lastEventId":"","cancelBubble":false,"data":"{\"stars\":[{\"x\":\"0.0\",\"y\":\"0.0\",\"own\":\"-1\",\"id\":\"0\",\"units\":\"0\"},{\"x\":\"0.0\",\"y\":\"0.0\",\"own\":\"-1\",\"id\":\"1\",\"units\":\"0\"},{\"x\":\"0.0\",\"y\":\"0.0\",\"own\":\"0\",\"id\":\"2\",\"units\":\"0\"}]}"} 

我有2個問題:

1)爲什麼該消息的第一部分(自動)有多少頭重複?這樣好嗎,我應該這樣離開嗎,還是可以以某種方式減少樣板的數量?

2)爲什麼郵件第二部分(我的有效載荷)中的所有引號都被轉義了?

下面是制定的JSON的代碼:

val stars = strs.getAll.map(_.asJsValue).toSeq 
Json.toJson(
    Map(
     "stars" -> stars 
     ) 
) 

asJsValue方法:

def asJsValue = { 
    Json.toJson(
     Map(
      "id" -> id.toString, 
      "x" -> x.toString, 
      "y" -> y.toString, 
      "units" -> units.toString, 
      "own" -> getOwnerID.toString 
     ) 
    ) 
    } 

和在客戶端:

websocket.onmessage = receivedEvent 

receiveEvent = (event) -> 
    console.log("WS-PARSER: received " + JSON.stringify(event)) 

回答

1
  1. 大多數該數據的在客戶端添加,只有data值在該線
  2. JSON需要雙引號發送,這就是爲什麼他們會被轉義

(聲明:不是打用戶)

+0

所以雙引號被轉義,因爲他們自己都在裏面這個名爲'data'的字符串和轉義斜槓在那裏,因爲字符串輸出到了屏幕上,而實際上它們不在那裏? 我的意思是,如果我使用'data'字符串作爲JSON,那麼一切都會好起來的,還是會陷入困境? – noncom

+0

你會如何表示不帶斜槓或其他轉義字符的嵌套引號? :)它們是通過'stringify'調用添加的。如果您打印/記錄/使用該字符串,您會看到它們「消失」。 'JSON.parse(message.data)'應該可以正常工作。 –