You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

69 lines
1.7 KiB

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

package main
import (
"bytes"
"dsBaseRpc/Utils/CommonUtil"
"dsBaseRpc/Utils/FileUtil"
"encoding/json"
"fmt"
"github.com/iancoleman/strcase"
"github.com/tidwall/gjson"
"os"
"path/filepath"
"reflect"
"strings"
)
//根据json对象字符串生成结构体
func createStruct(jsonStr string, structName string) string {
m := make(map[string]interface{})
err := json.Unmarshal([]byte(jsonStr), &m)
if err != nil {
fmt.Println("转化错误:", err)
}
var buffer bytes.Buffer
buffer.WriteString("type ")
buffer.WriteString(structName)
buffer.WriteString(" struct {\n")
for k, v := range m {
runes := []rune(k)
buffer.WriteString(strcase.ToCamel(string(runes))) //驼峰命名法
buffer.WriteString(" ")
buffer.WriteString((reflect.TypeOf(v)).String())
buffer.WriteString(" `json:\"")
buffer.WriteString(k)
buffer.WriteString("\"`")
buffer.WriteString("\n")
}
buffer.WriteString("}")
return buffer.String()
}
func main() {
//文件名称
fileName := `e:\\TBaseOrganization.json`
//1、读取json文件
j := FileUtil.ReadFileContent(fileName)
result := gjson.Get(j, "datas")
//2、生成JSON对应的struct
if len(result.Array()) == 0 {
fmt.Println("未找到数据无法生成Struct~")
os.Exit(200)
}
r1 := result.Array()[0]
fmt.Println(r1.Get("data_id"))
fmt.Println(r1.Get("del_flag"))
re := r1.Get("data")
jsonStr := re.Str
c := strings.Replace(filepath.Base(fileName), ".json", "", -1)
content := "package Struct\n" + createStruct(jsonStr, c)
parentPath, _ := os.Getwd()
parentPath = strings.Replace(parentPath, "\\", "/", -1)
//保存文件
p1 := parentPath + "/Test/TestFenXiJson/Struct/" + c + ".go"
FileUtil.WriteContent(p1, content)
//格式化文件
CommonUtil.Exec("gofmt", "-l", "-w", p1)
}