From c140c7d0ec81ad2b3336149d121c7c8abd79c91d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=99=BD=E8=8C=B6=E6=B8=85=E6=AC=A2?= Date: Thu, 9 Sep 2021 10:02:50 +0800 Subject: [PATCH] =?UTF-8?q?=E5=8A=A8=E6=80=81JSON=E5=A2=9E=E5=8A=A0ToMap,?= =?UTF-8?q?=20ToList,=20Receiver=E6=96=B9=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- json/build.go | 58 +++++++++++++++++++++++++++++++++++++++++---------- 1 file changed, 47 insertions(+), 11 deletions(-) diff --git a/json/build.go b/json/build.go index 5677fba..c6cdeba 100644 --- a/json/build.go +++ b/json/build.go @@ -8,6 +8,7 @@ package json import ( + "encoding/json" "fmt" "regexp" "strconv" @@ -84,18 +85,19 @@ func (dj *DynamicJSON) SetValue(path string, value interface{}, isComplexType bo for keyIndex, key := range pathList { searchRoot = dj.search(searchRoot, key) if nil != searchRoot { - searchRoot.Value = value // 查询到结果,更新值 + // 查询到结果,更新值 + searchRoot.Value = value parent = searchRoot - } else { - var val interface{} - if keyIndex == len(pathList)-1 { - val = value - } - _ = dj.createNode(parent, key, val, isComplexType) - if len(parent.Child) > 0 { - searchRoot = parent.Child[len(parent.Child)-1] - parent = parent.Child[len(parent.Child)-1] - } + continue + } + var val interface{} + if keyIndex == len(pathList)-1 { + val = value + } + _ = dj.createNode(parent, key, val, isComplexType) + if len(parent.Child) > 0 { + searchRoot = parent.Child[len(parent.Child)-1] + parent = parent.Child[len(parent.Child)-1] } } } @@ -112,6 +114,40 @@ func (dj *DynamicJSON) String() string { return fmt.Sprintf(strings.Join(*tplListResult, ""), *valListResult...) } +// Map 转化为map +// +// Author : go_developer@163.com<白茶清欢> +// +// Date : 9:59 上午 2021/9/9 +func (dj *DynamicJSON) Map() (map[string]interface{}, error) { + var res map[string]interface{} + err := json.Unmarshal([]byte(dj.String()), &res) + return res, err +} + +// Slice 转化为slice +// +// Author : go_developer@163.com<白茶清欢> +// +// Date : 9:59 上午 2021/9/9 +func (dj *DynamicJSON) Slice() ([]interface{}, error) { + var res []interface{} + err := json.Unmarshal([]byte(dj.String()), &res) + return res, err +} + +// ParseWithReceiver 使用指定结构解析 +// +// Author : go_developer@163.com<白茶清欢> +// +// Date : 10:01 上午 2021/9/9 +func (dj *DynamicJSON) ParseWithReceiver(receiver interface{}) error { + if nil == receiver { + return errors.New("receiver is nil") + } + return json.Unmarshal([]byte(dj.String()), receiver) +} + // buildTpl 构建json模版与绑定数据 // // Author : go_developer@163.com<白茶清欢>