我在解组访问 golang 服务中的 JSON 字符串的值时遇到问题。我阅读了 golang 的文档,但示例中的 JSON 对象的格式都不同。从我的 api 我得到以下 JSON 字符串:{"NewDepartment": { "newDepName":"Testabt", "newDepCompany":2, "newDepMail":"Bla@bla.org" }}在go中我定义了以下数据类型:type NewDepartment struct { NewDepName string `json:"newDepName"` NewDepCompany int `json:"newDepCompany"` NewDepMail string `json:"newDepMail"`}type NewDeps struct { NewDeps []NewDepartment `json:"NewDepartment"`}我尝试解组 JSON(来自请求正文)并访问值,但无法获得任何结果var data types.NewDepartment errDec := json.Unmarshal(reqBody, &data)fmt.Println("AddDepartment JSON string got: " + data.NewDepName)但它不包含字符串 - 不显示任何内容,但解组或 Println 上没有错误。
1 回答
![?](http://img1.sycdn.imooc.com/54585050000156a302200220-100-100.jpg)
米琪卡哇伊
TA贡献1998条经验 获得超6个赞
你快到了。
第一个更新是创建NewDeps.NewDeps
单个对象,而不是数组(根据提供的 JSON)。
第二个更新是将 JSON 反序列化为NewDeps
,而不是反序列化为NewDepartment
.
工作代码:
type NewDepartment struct {
NewDepName string `json:"newDepName"`
NewDepCompany int `json:"newDepCompany"`
NewDepMail string `json:"newDepMail"`
}
type NewDeps struct {
NewDeps NewDepartment `json:"NewDepartment"`
}
func main() {
var data NewDeps
json.Unmarshal([]byte(body), &data)
fmt.Println("AddDepartment JSON string got: " + data.NewDeps.NewDepName)
}
https://play.golang.org/p/Sn02hwETRv1
- 1 回答
- 0 关注
- 126 浏览
添加回答
举报
0/150
提交
取消