我在解組訪問 golang 服務中的 JSON 字符串的值時遇到問題。我閱讀了 golang 的文檔,但示例中的 JSON 對象的格式都不同。從我的 api 我得到以下 JSON 字符串:{"NewDepartment": { "newDepName":"Testabt", "newDepCompany":2, "newDepMail":"[email protected]" }}在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 回答

米琪卡哇伊
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 關注
- 150 瀏覽
添加回答
舉報
0/150
提交
取消