github.com/nibnait/go-learn@v0.0.0-20220227013611-dfa47ea6d2da/src/test/chapter/ch8/01_json/json_test.go (about) 1 package json 2 3 import ( 4 "encoding/json" 5 "fmt" 6 "testing" 7 ) 8 9 var jsonStr = `{ 10 "basic_info":{ 11 "name":"Mike", 12 "age":30 13 }, 14 "job_info":{ 15 "skills":["Java","Go","C"] 16 } 17 } ` 18 19 func TestEmbeddedJson(t *testing.T) { 20 e := new(Employee) 21 err := json.Unmarshal([]byte(jsonStr), e) 22 if err != nil { 23 t.Error(err) 24 } 25 fmt.Println(*e) 26 if v, err := json.Marshal(e); err == nil { 27 fmt.Println(string(v)) 28 } else { 29 t.Error(err) 30 } 31 32 } 33 34 func TestEasyJson(t *testing.T) { 35 e := Employee{} 36 e.UnmarshalJSON([]byte(jsonStr)) 37 fmt.Println(e) 38 if v, err := e.MarshalJSON(); err != nil { 39 t.Error(err) 40 } else { 41 fmt.Println(string(v)) 42 } 43 } 44 45 func BenchmarkEmbeddedJson(b *testing.B) { 46 b.ResetTimer() 47 e := new(Employee) 48 for i := 0; i < b.N; i++ { 49 50 err := json.Unmarshal([]byte(jsonStr), e) 51 if err != nil { 52 b.Error(err) 53 } 54 if _, err = json.Marshal(e); err != nil { 55 b.Error(err) 56 } 57 } 58 } 59 60 func BenchmarkEasyJson(b *testing.B) { 61 b.ResetTimer() 62 e := Employee{} 63 for i := 0; i < b.N; i++ { 64 err := e.UnmarshalJSON([]byte(jsonStr)) 65 if err != nil { 66 b.Error(err) 67 } 68 if _, err = e.MarshalJSON(); err != nil { 69 b.Error(err) 70 } 71 } 72 }