我正在尝试从 JSON 数组中获取每个 JSON 对象。我通过 HTTP post 获取这些数据。
我知道我的数据会是什么样子:
{
"array":[
{
"entity_title":"University of Phoenix",
"entity_org_name":"CS Club",
"possible_user_name":"Johnny Ive",
"posibble_user_email":"Johhny.Ive@uop.edu",
"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":"steven.job@uop.edu",
"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 对象。
最佳答案
试试这个作为你的结构,
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
也未正确命名。解码为 MsgCreateUserArray
后,您可以遍历 CreateUser
slice 以获取每个 MsgCreateUserJson
关于arrays - 解析 JSON 对象的 JSON 数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29325956/