我在讀取 json 數(shù)組時遇到了一個問題。需要以下查詢的幫助。請求 Json :{ "httpReq": {"username": "1234567890","password": "1234567890","number": "123456"}}響應 JSON :{ "httpResp": { "status": "Pass", "message": "great" } }下面是我的代碼:如果我在其工作下傳遞 json 對象,但我需要在 json 中發(fā)送“httpReq”。package mainimport ( "encoding/json" "fmt")type people struct { Username string `json:"username"` Password string `json:"password"` Number string `json:"number"` }type peopleread struct { Collection []people}func main() { text := `{ "username": "1234567890", "password": "1234567890", "number": "123456" }` textBytes := []byte(text) //people1 := people{} var people2 people err := json.Unmarshal(textBytes, &people2) if err != nil { fmt.Println(err) return } Username := people2.Username Password := people2.Password Number := people2.Number fmt.Println(Username) fmt.Println(Password) fmt.Println(Number) }
1 回答

幕布斯7119047
TA貢獻1794條經(jīng)驗 獲得超8個贊
要使用httpReq字段解組,您必須處理此問題。
創(chuàng)建一個結(jié)構(gòu)來包裝您的請求正文,例如 json
type HttpReq struct{
HttpReq people `json:"httpReq"`
}
然后使用解組
var httpReq HttpReq
err := json.Unmarshal(textBytes, &httpReq)
Go 游樂場的完整代碼在這里
- 1 回答
- 0 關(guān)注
- 303 瀏覽
添加回答
舉報
0/150
提交
取消