github.com/gogf/gf@v1.16.9/encoding/gjson/gjson_z_unit_json_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/encoding/gjson" 11 "github.com/gogf/gf/frame/g" 12 "github.com/gogf/gf/test/gtest" 13 "github.com/gogf/gf/text/gstr" 14 "testing" 15 ) 16 17 func Test_ToJson(t *testing.T) { 18 type ModifyFieldInfoType struct { 19 Id int64 `json:"id"` 20 New string `json:"new"` 21 } 22 type ModifyFieldInfosType struct { 23 Duration ModifyFieldInfoType `json:"duration"` 24 OMLevel ModifyFieldInfoType `json:"om_level"` 25 } 26 27 type MediaRequestModifyInfo struct { 28 Modify ModifyFieldInfosType `json:"modifyFieldInfos"` 29 Field ModifyFieldInfosType `json:"fieldInfos"` 30 FeedID string `json:"feed_id"` 31 Vid string `json:"id"` 32 } 33 34 gtest.C(t, func(t *gtest.T) { 35 jsonContent := `{"dataSetId":2001,"fieldInfos":{"duration":{"id":80079,"value":"59"},"om_level":{"id":2409,"value":"4"}},"id":"g0936lt1u0f","modifyFieldInfos":{"om_level":{"id":2409,"new":"4","old":""}},"timeStamp":1584599734}` 36 var info MediaRequestModifyInfo 37 err := gjson.DecodeTo(jsonContent, &info) 38 t.Assert(err, nil) 39 content := gjson.New(info).MustToJsonString() 40 t.Assert(gstr.Contains(content, `"feed_id":""`), true) 41 t.Assert(gstr.Contains(content, `"fieldInfos":{`), true) 42 t.Assert(gstr.Contains(content, `"id":80079`), true) 43 t.Assert(gstr.Contains(content, `"om_level":{`), true) 44 t.Assert(gstr.Contains(content, `"id":2409,`), true) 45 t.Assert(gstr.Contains(content, `"id":"g0936lt1u0f"`), true) 46 t.Assert(gstr.Contains(content, `"new":"4"`), true) 47 }) 48 } 49 50 func Test_MapAttributeConvert(t *testing.T) { 51 var data = ` 52 { 53 "title": {"l1":"标签1","l2":"标签2"} 54 } 55 ` 56 gtest.C(t, func(t *gtest.T) { 57 j, err := gjson.LoadContent(data) 58 gtest.Assert(err, nil) 59 60 tx := struct { 61 Title map[string]interface{} 62 }{} 63 64 err = j.Struct(&tx) 65 gtest.Assert(err, nil) 66 t.Assert(tx.Title, g.Map{ 67 "l1": "标签1", "l2": "标签2", 68 }) 69 }) 70 71 gtest.C(t, func(t *gtest.T) { 72 j, err := gjson.LoadContent(data) 73 gtest.Assert(err, nil) 74 75 tx := struct { 76 Title map[string]string 77 }{} 78 79 err = j.Struct(&tx) 80 gtest.Assert(err, nil) 81 t.Assert(tx.Title, g.Map{ 82 "l1": "标签1", "l2": "标签2", 83 }) 84 }) 85 }