
本文详解 go 语言中解析形如 {"array": [{...}, {...}]} 结构的 json 数据,涵盖结构体字段映射、标签修正、反序列化及遍历操作,并提供可直接运行的完整示例。
在 Go 中解析 JSON 数组时,关键在于结构体字段名与 JSON 键名严格对应,且需通过正确的 JSON 标签(json:"...")声明嵌套路径。你提供的原始数据是一个顶层 JSON 对象,其内嵌字段名为 "array"(而非 "createUserArray"),而数组中每个对象的字段如 "entity_title" 也需精准映射——任何拼写或命名不一致(例如误写为 "entity_title_name")都会导致反序列化失败或字段为空。
首先,修正结构体定义:
- 外层结构体 MsgCreateUserArray 的切片字段应使用 json:"array" 标签,而非 "createUserArray";
- 内层结构体 MsgCreateUserJson 的字段名需与 JSON 键一一匹配(注意 "posibble_user_email" 拼写错误需保留,因 JSON 原文如此);
- 推荐将数字型字段(如 msg_body_id)声明为 int64 或 int,并使用 omitempty 实现零值忽略;
- 邮箱字段含 HTML 标签,若需纯文本邮箱,后续应做 HTML 解析或正则提取(本文聚焦解析,暂不处理清洗逻辑)。
以下是修正后的完整可运行代码:
package main
import (
"encoding/json"
"fmt"
"log"
"net/http"
)
type MsgCreateUserArray struct {
CreateUser []MsgCreateUserJson `json:"array"`
}
type MsgCreateUserJson struct {
EntityTitle string `json:"entity_title"`
EntityOrgName string `json:"entity_org_name"`
PossibleUserName string `json:"possible_user_name"`
PosibbleUserEmail string `json:"posibble_user_email"` // 注意:原文拼写为 posibble(非 possible)
UserPositionTitle string `json:"user_position_title"`
MsgBodyID int64 `json:"msg_body_id,omitempty"`
}
func parseJson(rw http.ResponseWriter, request *http.Request) {
defer request.Body.Close() // 防止资源泄漏
decoder := json.NewDecoder(request.Body)
var msg MsgCreateUserArray
if err := decoder.Decode(&msg); err != nil {
http.Error(rw, "Invalid JSON: "+err.Error(), http.StatusBadRequest)
return
}
log.Printf("Parsed %d user entries", len(msg.CreateUser))
// 遍历每个 JSON 对象并处理
for i, user := range msg.CreateUser {
fmt.Fprintf(rw, "Entry %d:\n", i+1)
fmt.Fprintf(rw, "- Entity: %s (%s)\n", user.EntityTitle, user.EntityOrgName)
fmt.Fprintf(rw, "- Contact: %s / %s\n", user.PossibleUserName, user.PosibbleUserEmail)
fmt.Fprintf(rw, "- Position: %s (ID: %d)\n\n", user.UserPositionTitle, user.MsgBodyID)
}
}
func main() {
http.HandleFunc("/", parseJson)
log.Println("Server starting on :1337...")
log.Fatal(http.ListenAndServe(":1337", nil))
}使用说明与注意事项:
✅ 测试方法:启动服务后,用 curl 发送示例 JSON:
curl -X POST http://localhost:1337 \
-H "Content-Type: application/json" \
-d '{
"array": [
{
"entity_title":"University of Phoenix",
"entity_org_name":"CS Club",
"possible_user_name":"Johnny Ive",
"posibble_user_email":"johnny@example.com",
"user_position_title":"President",
"msg_body_id":4
}
]
}'⚠️ 常见陷阱提醒:
- 字段标签大小写敏感("EntityTitle" 对应 "entity_title",而非 "Entity_Title");
- 若 JSON 中存在空值或缺失字段,建议为字符串字段添加 omitempty 并初始化为零值,避免空字符串干扰业务逻辑;
- msg_body_id 在示例中为整数,但原始结构体声明为 string 会导致解析失败——务必保持类型一致;
- 生产环境务必添加 defer request.Body.Close() 防止连接泄漏。
掌握此模式后,你可轻松扩展处理任意深度嵌套的 JSON 数组,如分页响应({"data": [...], "meta": {...}})或树形结构数据。核心原则始终是:结构即契约,标签即桥梁,类型即保障。










