golang 如何将多层级的被jsonencode的字符串加载到结构体
在 Golang 中,可以使用 json.Unmarshal() 函数将多层级的 JSON 字符串加载到结构体中。下面是一个示例:
package main
import (
"encoding/json"
"fmt"
)
type User struct {
ID int `json:"id"`
Name string `json:"name"`
Age int `json:"age"`
}
type Response struct {
Users []User `json:"users"`
}
func main() {
jsonStr := `{"users":[{"id":1,"name":"Alice","age":25},{"id":2,"name":"Bob","age":30}]}`
var response Response
err := json.Unmarshal([]byte(jsonStr), &response)
if err != nil {
fmt.Println("Error:", err)
return
}
fmt.Println(response.Users)
}
在上述示例中,Response 结构体包含一个 Users 字段,该字段是一个 User 结构体的切片。使用 json.Unmarshal() 函数将 JSON 字符串解码到 response 变量中,即可将多层级的 JSON 字符串加载到结构体中。
运行上述代码,输出结果为:
[{1 Alice 25} {2 Bob 30}]
这里将 JSON 字符串解码为结构体,所以 response.Users 就是一个包含两个 User 结构体的切片
原文地址: https://www.cveoy.top/t/topic/imTO 著作权归作者所有。请勿转载和采集!