github.com/gogf/gf@v1.16.9/encoding/gjson/gjson_z_unit_implements_test.go (about) 1 // Copyright GoFrame Author(https://goframe.org). All Rights Reserved. 2 // 3 // This Source Code Form is subject to the terms of the MIT License. 4 // If a copy of the MIT was not distributed with this file, 5 // You can obtain one at https://github.com/gogf/gf. 6 7 package gjson_test 8 9 import ( 10 "github.com/gogf/gf/internal/json" 11 "github.com/gogf/gf/util/gconv" 12 "testing" 13 14 "github.com/gogf/gf/encoding/gjson" 15 "github.com/gogf/gf/frame/g" 16 "github.com/gogf/gf/test/gtest" 17 ) 18 19 func TestJson_UnmarshalJSON(t *testing.T) { 20 data := []byte(`{"n":123456789, "m":{"k":"v"}, "a":[1,2,3]}`) 21 gtest.C(t, func(t *gtest.T) { 22 j := gjson.New(nil) 23 err := json.UnmarshalUseNumber(data, j) 24 t.Assert(err, nil) 25 t.Assert(j.Get("n"), "123456789") 26 t.Assert(j.Get("m"), g.Map{"k": "v"}) 27 t.Assert(j.Get("m.k"), "v") 28 t.Assert(j.Get("a"), g.Slice{1, 2, 3}) 29 t.Assert(j.Get("a.1"), 2) 30 }) 31 } 32 33 func TestJson_UnmarshalValue(t *testing.T) { 34 type V struct { 35 Name string 36 Json *gjson.Json 37 } 38 // JSON 39 gtest.C(t, func(t *gtest.T) { 40 var v *V 41 err := gconv.Struct(g.Map{ 42 "name": "john", 43 "json": []byte(`{"n":123456789, "m":{"k":"v"}, "a":[1,2,3]}`), 44 }, &v) 45 t.Assert(err, nil) 46 t.Assert(v.Name, "john") 47 t.Assert(v.Json.Get("n"), "123456789") 48 t.Assert(v.Json.Get("m"), g.Map{"k": "v"}) 49 t.Assert(v.Json.Get("m.k"), "v") 50 t.Assert(v.Json.Get("a"), g.Slice{1, 2, 3}) 51 t.Assert(v.Json.Get("a.1"), 2) 52 }) 53 // Map 54 gtest.C(t, func(t *gtest.T) { 55 var v *V 56 err := gconv.Struct(g.Map{ 57 "name": "john", 58 "json": g.Map{ 59 "n": 123456789, 60 "m": g.Map{"k": "v"}, 61 "a": g.Slice{1, 2, 3}, 62 }, 63 }, &v) 64 t.Assert(err, nil) 65 t.Assert(v.Name, "john") 66 t.Assert(v.Json.Get("n"), "123456789") 67 t.Assert(v.Json.Get("m"), g.Map{"k": "v"}) 68 t.Assert(v.Json.Get("m.k"), "v") 69 t.Assert(v.Json.Get("a"), g.Slice{1, 2, 3}) 70 t.Assert(v.Json.Get("a.1"), 2) 71 }) 72 }