升级json操作, 升级为面向接口实现 #10

Merged
zhangdeman merged 7 commits from feature/upgrade_get_set into master 2025-05-06 14:14:30 +08:00
2 changed files with 79 additions and 1 deletions
Showing only changes of commit 1124ff6a33 - Show all commits

View File

@ -10,11 +10,15 @@ package abstract
// IJsonWrite json数据写入
type IJsonWrite interface {
// Set 设置一个路径的值
Set(dataPath string, data interface{}) error
Set(dataPath string, data any) error
// Result 最终结果以字符串形式返回
Result() string
// Map 最终结果以map返回
Map() (map[string]any, error)
// MapWithReceiver 外部指针接收返回值
MapWithReceiver(receiver any) error
// Array 最终结果以数组返回
Array() ([]any, error)
// ArrayWithReceiver 外部指针接收返回值
ArrayWithReceiver(receiver any) error
}

74
implement/sjson_write.go Normal file
View File

@ -0,0 +1,74 @@
// Package implement ...
//
// Description : implement ...
//
// Author : go_developer@163.com<白茶清欢>
//
// Date : 2025-05-06 11:53
package implement
import (
"git.zhangdeman.cn/zhangdeman/json_filter/abstract"
"git.zhangdeman.cn/zhangdeman/serialize"
"github.com/tidwall/sjson"
"sync"
)
func NewSjsonWrite() abstract.IJsonWrite {
return &SjsonWrite{
res: "",
l: &sync.RWMutex{},
}
}
type SjsonWrite struct {
res string
l *sync.RWMutex
}
func (s *SjsonWrite) Set(dataPath string, data any) error {
var (
err error
)
s.l.Lock()
defer s.l.Unlock()
if s.res, err = sjson.Set(s.res, dataPath, data); nil != err {
return err
}
return nil
}
func (s *SjsonWrite) Result() string {
return s.res
}
func (s *SjsonWrite) Map() (map[string]any, error) {
var (
mapRes map[string]any
err error
)
if err = s.MapWithReceiver(&mapRes); nil != err {
return nil, err
}
return mapRes, nil
}
func (s *SjsonWrite) MapWithReceiver(receiver any) error {
return serialize.JSON.UnmarshalWithNumberForString(s.res, receiver)
}
func (s *SjsonWrite) Array() ([]any, error) {
var (
arrRes []any
err error
)
if err = s.ArrayWithReceiver(&arrRes); nil != err {
return nil, err
}
return arrRes, nil
}
func (s *SjsonWrite) ArrayWithReceiver(receiver any) error {
return serialize.JSON.UnmarshalWithNumberForString(s.res, receiver)
}