我試圖從 JSON 數組中獲取每個 JSON 對象。我通過 HTTP 帖子獲取這些數據。我知道我的數據會是什么樣子: { "array":[ { "entity_title":"University of Phoenix", "entity_org_name":"CS Club", "possible_user_name":"Johnny Ive", "posibble_user_email":"[email protected]", "user_position_title":"President", "msg_body_id":4 }, { "entity_title":"University of San Francisco", "entity_org_name":"Marketing club", "possible_user_name":"steve jobs", "posibble_user_email":"[email protected]", "user_position_title":"Student", "msg_body_id":5 } ] }我的示例代碼和結構如下所示: type MsgCreateUserArray struct { CreateUser []MsgCreateUserJson `json:"createUserArray"` } type MsgCreateUserJson struct { EntityTitleName string `json:"entity_title_name"` EntityOrgName string `json:"entity_org_name"` PossibleUserName string `json:"possible_user_name"` PossibleUserEmail string `json:"possible_user_email"` UserPositionTitle string `json:"user_position_title"` MsgBodyId string `json:"msg_body_id, omitempty"` }func parseJson(rw http.ResponseWriter, request *http.Request) { decodeJson := json.NewDecoder(request.Body) var msg MsgCreateUserArray err := decodeJson.Decode(&msg) if err != nil { panic(err) } log.Println(msg.CreateUser)}func main() { http.HandleFunc("/", parseJson) http.ListenAndServe(":1337", nil)}我不確定如何遍歷 JSON 數組并獲取 JSON 對象,然后只使用 JSON 對象。
1 回答

郎朗坤
TA貢獻1921條經驗 獲得超9個贊
試試這個作為你的結構,
type MsgCreateUserArray struct {
CreateUser []MsgCreateUserJson `json:"array"`
}
type MsgCreateUserJson struct {
EntityOrgName string `json:"entity_org_name"`
EntityTitle string `json:"entity_title"`
MsgBodyID int64 `json:"msg_body_id,omitempty"`
PosibbleUserEmail string `json:"posibble_user_email"`
PossibleUserName string `json:"possible_user_name"`
UserPositionTitle string `json:"user_position_title"`
}
您的entity_title_name名稱不正確,頂級array. 解碼成 a 后,MsgCreateUserArray您可以遍歷CreateUser切片以獲取每個MsgCreateUserJson
- 1 回答
- 0 關注
- 182 瀏覽
添加回答
舉報
0/150
提交
取消