Go语言如何反序列化二维数组?解决JSON反序列化报错
解决Go Gin中JSON二维数组反序列化问题
问题根源
你的JSON payload里specifications是二维字符串数组(数组嵌套数组),但Product结构体中Specifications字段定义为*[]string(指向一维字符串数组的指针),类型不匹配导致反序列化失败,触发报错json: cannot unmarshal array into Go struct field Product.specifications of type string。
修正方案
直接把Product结构体里的Specifications字段类型改为*[][]string(指向二维字符串数组的指针),和JSON结构完全对应:
type Product struct { ID primitive.ObjectID `json:"_id" bson:"_id"` Product_Id *string `json:"user_id"` Category *string `json:"category"` Name *string `json:"name"` Color *[]Color `json:"color"` Size *[]string `json:"size"` Specifications *[][]string `json:"specifications"` // 改为二维数组指针类型 Product_Images ProductImage `json:"product_image"` Product_Accessories *[]string `json:"product_accessories"` Product_Price ProductPrice `json:"product_price"` }
关于自定义Specifications结构体的说明
你之前尝试定义的Specifications结构体属于冗余包装——JSON本身就是直接的二维数组,用[][]string或其指针类型最简洁。如果一定要用自定义结构体,需保证结构和JSON匹配,但会增加不必要的嵌套:
// 仅在有额外业务逻辑需求时使用 type SpecificationItem []string type Specifications []SpecificationItem // 对应Product结构体字段修改为: Specifications *Specifications `json:"specifications"`
验证修改
调整结构体类型后,c.BindJSON(&payload)就能正确将JSON中的二维数组反序列化到Specifications字段,后续插入MongoDB的逻辑也能正常执行。
内容的提问来源于stack exchange,提问作者Abhinay Narayan Singh
相关产品推荐
相关产品推荐

