duandao2306 2015-03-29 05:30
浏览 80
已采纳

解析JSON对象的JSON数组?

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)
}

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.

  • 写回答

1条回答 默认 最新

  • duan0708676887 2015-03-29 06:07
    关注

    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"`
    }
    

    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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 我要一个分身加定位两个功能的安卓app
  • ¥15 基于FOC驱动器,如何实现卡丁车下坡无阻力的遛坡的效果
  • ¥15 IAR程序莫名变量多重定义
  • ¥15 (标签-UDP|关键词-client)
  • ¥15 关于库卡officelite无法与虚拟机通讯的问题
  • ¥15 目标检测项目无法读取视频
  • ¥15 GEO datasets中基因芯片数据仅仅提供了normalized signal如何进行差异分析
  • ¥100 求采集电商背景音乐的方法
  • ¥15 数学建模竞赛求指导帮助
  • ¥15 STM32控制MAX7219问题求解答