解析JSON对象的JSON数组? [英] Parsing a JSON array of JSON objects?

查看:177
本文介绍了解析JSON对象的JSON数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从JSON数组中获取每个JSON对象.我通过HTTP发布获得了这些数据.

I am trying to get each JSON object out of a JSON array. I get this data via a HTTP post.

我知道我的数据是什么样的:

I know what my data will look like:

   {
    "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
      }
    ]
  }

我的示例代码和结构如下:

My example code and my structs look like this:

    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对象.

I am not sure where how to iterate over the JSON array and get the JSON objects and then just work with the JSON objects.

推荐答案

尝试将其作为您的结构,

Try this as your structs,

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

Your entity_title_name is not named correctly, nor is the top level array. After you decode into a MsgCreateUserArray you can iterate over the CreateUser slice to get each MsgCreateUserJson

这篇关于解析JSON对象的JSON数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆