2013-06-25 18 views
7

Alla luce di questi casi due test:Test per profonda uguaglianza con JSON marshaling in golang

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

Dove l'aiutante testMarshalUnmarshal marescialli solo per JSON e tornare indietro:

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() 
    } 
} 

Perché il primo banco di prova passare e il secondo fallire? L'uscita del test è questo:

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 modo da poter avere un hack a facilmente.

risposta

13

L'ho capito! JSON ha solo un tipo numerico, che è in virgola mobile, quindi tutti gli interi vengono convertiti in Float64 nel processo marshal/unmarshal. Quindi, nella mappa res, il 5 è un float64 invece di un int.

Here è un campo di gioco che fornisce il contesto e la prova di ciò di cui sto parlando.