支持通过配置传入XmlName, 默认值 XmlData
This commit is contained in:
parent
f9024b9498
commit
b4932bf7cd
@ -10,12 +10,13 @@ package wrapper
|
||||
import (
|
||||
"encoding/xml"
|
||||
"errors"
|
||||
"fmt"
|
||||
dynamicstruct "git.zhangdeman.cn/zhangdeman/dynamic-struct"
|
||||
"git.zhangdeman.cn/zhangdeman/serialize"
|
||||
"github.com/tidwall/gjson"
|
||||
)
|
||||
|
||||
func NewJson(sourceData string) (*ownJson, error) {
|
||||
func NewJson(sourceData string, o *Option) (*ownJson, error) {
|
||||
gjsonRes := gjson.Parse(sourceData)
|
||||
if gjsonRes.Value() == nil {
|
||||
return nil, errors.New("source data parse result is nil")
|
||||
@ -24,10 +25,17 @@ func NewJson(sourceData string) (*ownJson, error) {
|
||||
if !gjsonRes.IsObject() {
|
||||
return nil, errors.New("source result is not map or struct Marshal string")
|
||||
}
|
||||
if nil == o {
|
||||
o = &Option{}
|
||||
}
|
||||
if o.XmlName == "" {
|
||||
o.XmlName = "XmlData"
|
||||
}
|
||||
oj := &ownJson{
|
||||
sourceData: sourceData,
|
||||
gjsonResult: gjsonRes,
|
||||
structBuilder: dynamicstruct.NewStruct(nil),
|
||||
o: o,
|
||||
}
|
||||
if err := oj.GenerateStruct(); nil != err {
|
||||
return nil, err
|
||||
@ -40,6 +48,7 @@ type ownJson struct {
|
||||
gjsonResult gjson.Result // 数据源解析为gjson
|
||||
structBuilder dynamicstruct.IBuilder // 结构体构造器
|
||||
structRes any // 解析的结构体值
|
||||
o *Option // 一些操作选项
|
||||
}
|
||||
|
||||
// GenerateStruct 生成结构体字段列表
|
||||
@ -49,7 +58,7 @@ func (oj *ownJson) GenerateStruct() error {
|
||||
return true
|
||||
})
|
||||
// 追加xml的标签
|
||||
oj.structBuilder.AddField("XMLName", "", xml.Name{}, `json:"-" xml:"XmlData"`, false)
|
||||
oj.structBuilder.AddField("XMLName", "", xml.Name{}, fmt.Sprintf(`json:"-" toml:"-" yml:"-" init:"-" xml:"%v"`, oj.o.XmlName), false)
|
||||
val := oj.structBuilder.Build().New()
|
||||
if err := serialize.JSON.UnmarshalWithNumber([]byte(oj.sourceData), &val); nil != err {
|
||||
return err
|
||||
|
@ -14,7 +14,7 @@ import (
|
||||
|
||||
func TestNewJson(t *testing.T) {
|
||||
sourceData := `{"name": "test", "age":18,"company":{"address": "Beijing", "name":"lala"},"index":[1,2,3,4], "deep":[{"name":"a"}]}`
|
||||
instance, iErr := NewJson(sourceData)
|
||||
instance, iErr := NewJson(sourceData, &Option{XmlName: "ResponseData"})
|
||||
fmt.Println(iErr)
|
||||
res, err := instance.Marshal("xml")
|
||||
fmt.Println(err)
|
||||
|
13
wrapper/option.go
Normal file
13
wrapper/option.go
Normal file
@ -0,0 +1,13 @@
|
||||
// Package wrapper ...
|
||||
//
|
||||
// Description : wrapper ...
|
||||
//
|
||||
// Author : go_developer@163.com<白茶清欢>
|
||||
//
|
||||
// Date : 2025-04-28 17:35
|
||||
package wrapper
|
||||
|
||||
// Option 生成结构体之后的可用选项
|
||||
type Option struct {
|
||||
XmlName string `json:"xml_name"` // 如果目标格式是 xml, 必须指定xmlName作为根节点
|
||||
}
|
Loading…
x
Reference in New Issue
Block a user