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 sub地址DHCP问题
  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办
  • ¥15 kylin启动报错log4j类冲突
  • ¥15 超声波模块测距控制点灯,灯的闪烁很不稳定,经过调试发现测的距离偏大