动态JSON增加ToMap, ToList, Receiver方法

This commit is contained in:
白茶清欢 2021-09-09 10:02:50 +08:00
parent f3170976fd
commit c140c7d0ec

View File

@ -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<白茶清欢>