gitee.com/go-spring2/spring-base@v1.1.3/json/json_test.go (about) 1 /* 2 * Copyright 2012-2019 the original author or authors. 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * https://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 package json_test 18 19 import ( 20 "bytes" 21 stdJson "encoding/json" 22 "testing" 23 24 "gitee.com/go-spring2/spring-base/assert" 25 "gitee.com/go-spring2/spring-base/json" 26 ) 27 28 func TestJSON(t *testing.T) { 29 30 var ss []string 31 err := json.Unmarshal([]byte(`{}`), &ss) 32 assert.Error(t, err, "json: cannot unmarshal object into Go value of type \\[\\]string") 33 34 _, err = json.Marshal(complex(1.0, 0.5)) 35 assert.Error(t, err, "json: unsupported type: complex128") 36 37 _, err = json.MarshalIndent(complex(1.0, 0.5), "", " ") 38 assert.Error(t, err, "json: unsupported type: complex128") 39 40 m := map[string]string{"a": "3"} 41 b, err := json.Marshal(m) 42 assert.Nil(t, err) 43 assert.Equal(t, string(b), `{"a":"3"}`) 44 45 b, err = json.MarshalIndent(m, "", " ") 46 assert.Nil(t, err) 47 assert.Equal(t, string(b), "{\n \"a\": \"3\"\n}") 48 49 m = map[string]string{} 50 err = json.Unmarshal([]byte(`{"b":"5"}`), &m) 51 assert.Nil(t, err) 52 assert.Equal(t, m, map[string]string{"b": "5"}) 53 54 w := bytes.NewBuffer(nil) 55 e := json.NewEncoder(w) 56 { 57 e1 := e.(*json.WrapEncoder).E.(*stdJson.Encoder) 58 e1.SetIndent("", " ") 59 } 60 err = e.Encode(m) 61 assert.Nil(t, err) 62 assert.Equal(t, w.String(), "{\n \"b\": \"5\"\n}\n") 63 64 err = e.Encode(complex(1.0, 0.5)) 65 assert.Error(t, err, "json: unsupported type: complex128") 66 67 r := bytes.NewReader([]byte("{\n \"b\": \"3\"\n}\n")) 68 d := json.NewDecoder(r) 69 { 70 d1 := d.(*json.WrapDecoder).D.(*stdJson.Decoder) 71 d1.UseNumber() 72 } 73 err = d.Decode(&m) 74 assert.Nil(t, err) 75 assert.Equal(t, m, map[string]string{"b": "3"}) 76 77 r.Reset([]byte(`{"a":"3"}`)) 78 err = d.Decode(&ss) 79 assert.Error(t, err, "json: cannot unmarshal object into Go value of type \\[\\]string") 80 }