如何在 golang 中解组 JSON
How to unmarshall JSON in golang
我无法解组访问我的 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 时没有错误。
感谢您的帮助。
你快到了。
第一次更新是使 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)
}
我无法解组访问我的 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 时没有错误。
感谢您的帮助。
你快到了。
第一次更新是使 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)
}