如何在 golang 中解组 JSON

我在解组访问 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 上没有错误。


扬帆大鱼
浏览 127回答 1
1回答

米琪卡哇伊

你快到了。第一个更新是创建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
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go