动态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 package json
import ( import (
"encoding/json"
"fmt" "fmt"
"regexp" "regexp"
"strconv" "strconv"
@ -84,18 +85,19 @@ func (dj *DynamicJSON) SetValue(path string, value interface{}, isComplexType bo
for keyIndex, key := range pathList { for keyIndex, key := range pathList {
searchRoot = dj.search(searchRoot, key) searchRoot = dj.search(searchRoot, key)
if nil != searchRoot { if nil != searchRoot {
searchRoot.Value = value // 查询到结果,更新值 // 查询到结果,更新值
searchRoot.Value = value
parent = searchRoot parent = searchRoot
} else { continue
var val interface{} }
if keyIndex == len(pathList)-1 { var val interface{}
val = value if keyIndex == len(pathList)-1 {
} val = value
_ = dj.createNode(parent, key, val, isComplexType) }
if len(parent.Child) > 0 { _ = dj.createNode(parent, key, val, isComplexType)
searchRoot = parent.Child[len(parent.Child)-1] if len(parent.Child) > 0 {
parent = parent.Child[len(parent.Child)-1] 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...) 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模版与绑定数据 // buildTpl 构建json模版与绑定数据
// //
// Author : go_developer@163.com<白茶清欢> // Author : go_developer@163.com<白茶清欢>