2013-06-25 66 views
7

JSON編組深平等鑑於這兩個測試用例:測試與在golang

func TestEqualWhat(t *testing.T) { 
    testMarshalUnmarshal(t, map[string]interface{}{"a":"b"}) 
    testMarshalUnmarshal(t, map[string]interface{}{"a":5}) 
} 

凡testMarshalUnmarshal助手只是乘警JSON和回退:

func testMarshalUnmarshal(t *testing.T, in map[string]interface{}) { 
    //marshal the object to a string 
    jsb, err := json.Marshal(in); 
    if err != nil { 
     log.Printf("Unable to marshal msg") 
     t.FailNow() 
    } 

    //unmarshal to a map 
    res := make(map[string]interface{}) 
    if err := json.Unmarshal(jsb, &res); err != nil { t.FailNow() } 

    if !reflect.DeepEqual(in, res) { 
     log.Printf("\nExpected %#v\nbut got %#v", in, res) 
     t.FailNow() 
    } 
} 

爲什麼第一個測試用例第二次失敗?測試的輸出是這樣的:

Expected map[string]interface {}{"a":5} 
but got map[string]interface {}{"a":5} 
--- FAIL: TestEqualWhat (0.00 seconds) 

Here is similar code on the go playground這樣你就可以在它有一個黑客容易。

回答

13

我想通了! JSON只有一個數值類型,它是浮點數,因此所有整數都會在編組/解組過程中轉換爲Float64。所以,在res映射中,5是float64而不是int。

Here是一個去操場,提供我在說什麼的背景和證據。