如何在golang中解组JSON

问题描述 投票:1回答:1

我在golang服务中无法解组访问json字符串的值。

我阅读了golang的文档,但是示例中的json对象的格式都不同。

从我的API中,我得到以下JSON字符串:

{"NewDepartment":
    {
    "newDepName":"Testabt",
    "newDepCompany":2,
    "newDepMail":"[email protected]"
    }
}

我定义了以下数据类型:

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时没有错误。

感谢您的帮助。

json go unmarshalling
1个回答
2
投票

您快到了。

第一次更新是使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

© www.soinside.com 2019 - 2024. All rights reserved.