{"title":"Golang: 将多层级 JSON 字符串加载到结构体 | 详细指南","description":"本指南详细介绍了在 Golang 中如何使用 json.Unmarshal() 函数将多层级的 JSON 字符串加载到结构体中,并提供了一个示例代码和运行结果。","keywords":"Golang, JSON, 结构体, 解码, Unmarshal, 多层级, 示例代码","content":""Golang: 将多层级 JSON 字符串加载到结构体 | 详细指南"\n\n在 Golang 中,可以使用 json.Unmarshal() 函数将多层级的 JSON 字符串加载到结构体中。下面是一个示例:\n\ngo\npackage main\n\nimport (\n\t"encoding/json"\n\t"fmt"\n)\n\ntype User struct {\n\tID int `json:\"id\"`\n\tName string `json:\"name\"`\n\tAge int `json:\"age\"`\n}\n\ntype Response struct {\n\tUsers []User `json:\"users\"`\n}\n\nfunc main() {\n\tjsonStr := `\"{\"users\":[\"{\"id\":1,\"name\":\"Alice\",\"age\":25}\",\"{\"id\":2,\"name\":\"Bob\",\"age\":30}\"]}\"`\n\t\n\tvar response Response\n\terr := json.Unmarshal([]byte(jsonStr), &response)\n\tif err != nil {\n\t\tfmt.Println(\"Error:\", err)\n\t\treturn\n\t}\n\t\n\tfmt.Println(response.Users)\n}\n\n\n在上述示例中,Response 结构体包含一个 Users 字段,该字段是一个 User 结构体的切片。使用 json.Unmarshal() 函数将 JSON 字符串解码到 response 变量中,即可将多层级的 JSON 字符串加载到结构体中。\n\n运行上述代码,输出结果为:\n\n\n[{1 Alice 25} {2 Bob 30}]\n\n\n这里将 JSON 字符串解码为结构体,所以 response.Users 就是一个包含两个 User 结构体的切片。\n\n注意: 在使用 json.Unmarshal() 函数时,需要确保 JSON 字符串的格式与结构体字段的 json 标签相匹配。如果格式不匹配,将会导致解码错误。

Golang: 将多层级 JSON 字符串加载到结构体 | 详细指南

原文地址: https://www.cveoy.top/t/topic/p4Ue 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录