解析JSON对象数组?

8

我将尝试从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对象即可。


你有收到任何错误吗?你能把它发出来吗? - MIkCode
不,我得到的响应看起来像这样:2015/03/29 01:01:14 [{凤凰城大学CS俱乐部Johnny Ive Johhny.Ive@uop.edu主席} {旧金山大学市场营销俱乐部史蒂夫·乔布斯steven.job@uop.edu学生}] - surfin Array
字段名称不匹配(例如,您有 json:“entity_title_name”,但您的 json 为“entitiy_title”,以及 createUserArrayarray);某些字段类型错误(例如,您的 MsgBodyId string 但 JSON 却是数字类型);结构标签中不应包含空格(例如,从 json:“msg_body_id, omitempty” 中删除空格)......等等。 - Dave C
1个回答

10

尝试将此作为您的结构体:

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切片以获取每个MsgCreateUserJson


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接