golang自学之路(通过json字符串生成struct结构体)10

//jsonStr为json对象字符串{"key":"value"}
//structName 为要生成结构体的名称

 

//根据json对象字符串生成结构体
func createStruct(jsonStr string,structName 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(strings.ToUpper(string(runes[0])))
		buffer.WriteString(string(runes[1:]))
		buffer.WriteString("   ")
		buffer.WriteString(Typeof(v))
		buffer.WriteString("     `json:\"")
		buffer.WriteString(k)
		buffer.WriteString("\"`")
		buffer.WriteString("\n")
	}
	buffer.WriteString("}")
	fmt.Println(buffer.String())
}

 

你可能感兴趣的:(go)