Go GORM: JSON 字符串解析到结构体
可以使用 json.Unmarshal() 函数将 JSON 字符串解析到结构体中。以下是一个示例代码:
package main
import (
"encoding/json"
"fmt"
)
type Person struct {
Name string `json:"name"`
Age int `json:"age"`
Address struct {
City string `json:"city"`
Country string `json:"country"`
} `json:"address"`
}
func main() {
jsonString := `{"name":"John Doe","age":30,"address":{"city":"New York","country":"USA"}}`
var person Person
err := json.Unmarshal([]byte(jsonString), &person)
if err != nil {
fmt.Println("Error:", err)
} else {
fmt.Println(person)
}
}
在上面的代码中,我们定义了一个结构体 Person,其中包含一个名为 Address 的嵌套结构体。然后,我们使用 json.Unmarshal() 函数将 JSON 字符串解析到 person 变量中。在解析完成后,我们打印出 person 变量的值。输出结果如下:
{John Doe 30 {New York USA}}
注意,结构体中的字段名必须与 JSON 字符串中的键名相匹配,否则无法正确解析。为了确保匹配,我们可以在结构体字段的定义上使用 json:"键名" 标记。在上面的代码中,我们使用了这个标记来映射 JSON 字符串中的键名到结构体字段名。
原文地址: https://www.cveoy.top/t/topic/lKft 著作权归作者所有。请勿转载和采集!