diff --git a/tool/json2go/parser.go b/tool/json2go/parser.go new file mode 100644 index 0000000..6fc7f90 --- /dev/null +++ b/tool/json2go/parser.go @@ -0,0 +1,135 @@ +// Package json2go ... +// +// Description : json2go ... +// +// Author : go_developer@163.com<白茶清欢> +// +// Date : 2021-11-09 3:44 下午 +package json2go + +import ( + "fmt" + "strings" + + "git.zhangdeman.cn/zhangdeman/gopkg/util" + + "github.com/pkg/errors" + "github.com/tidwall/gjson" +) + +var ( + // structName 结构体名称 + structName = "Automatic" +) + +// NewJSON2GO ... +// +// Author : go_developer@163.com<白茶清欢> +// +// Date : 6:13 下午 2021/11/9 +func NewJSON2GO(name string) *JSON2GO { + if len(name) == 0 { + name = structName + } + return &JSON2GO{ + structName: name, + result: "type " + name + " struct { \n", + } +} + +// JSON2GO ... +// +// Author : go_developer@163.com<白茶清欢> +// +// Date : 6:12 下午 2021/11/9 +type JSON2GO struct { + structName string + result string +} + +// Parse ... +// +// Author : go_developer@163.com<白茶清欢> +// +// Date : 3:44 下午 2021/11/9 +func (jg *JSON2GO) Parse(inputJSON string) (string, error) { + if !gjson.Valid(inputJSON) { + return "", errors.New("input json is invalid") + } + parseResult := gjson.Parse(inputJSON) + if parseResult.IsArray() { + jg.parseArray("", parseResult) + } else { + jg.parseObject("", parseResult) + } + jg.result += "}" + return jg.result, nil +} + +// parseArray 解析array +// +// Author : go_developer@163.com<白茶清欢> +// +// Date : 4:37 下午 2021/11/9 +func (jg *JSON2GO) parseArray(key string, parseResult gjson.Result) string { + for _, v := range parseResult.Array() { + if v.IsObject() { + jg.parseObject(key, v) + } else if v.IsArray() { + jg.parseArray("", v) + } else { + jg.result += util.SnakeCaseToCamel(key) + " " + v.Type.String() + " `json:\"" + key + "\"`" + } + } + return "" +} + +// parseObject 解析object +// +// Author : go_developer@163.com<白茶清欢> +// +// Date : 4:37 下午 2021/11/9 +func (jg *JSON2GO) parseObject(key string, parseResult gjson.Result) string { + if len(key) > 0 { + jg.result += util.SnakeCaseToCamel(key) + " struct { \n" + } + for k, v := range parseResult.Map() { + if v.IsObject() { + jg.parseObject(k, v) + } else if v.IsArray() { + jg.parseArray(k, v) + } else { + jg.result += util.SnakeCaseToCamel(k) + " " + jg.getDataType(v) + " `json:\"" + k + "\"`\n" + } + } + if len(key) > 0 { + jg.result += " } `json:\"" + key + "\"`\n" + } + return "" +} + +// getDataType 获取数据类型 +// +// Author : go_developer@163.com<白茶清欢> +// +// Date : 8:14 下午 2021/11/9 +func (jg *JSON2GO) getDataType(val gjson.Result) string { + switch val.Type { + case gjson.True: + fallthrough + case gjson.False: + return "bool" + case gjson.Null: + return "map[string]interface{}" + case gjson.String: + return "string" + case gjson.Number: + tmpVal := fmt.Sprintf("%v", val.Num) + if strings.Contains(tmpVal, ".") { + return "float64" + } + return "int64" + default: + return "interface{}" + } +}