arrays - 解析 JSON 对象的 JSON 数组?

标签 arrays json go

我正在尝试从 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/

相关文章:

c - 如果我输入负数,则 1's complement, why it doesn' t 会起作用

reflection - 如何使用反射按名称获取包常量值?

pointers - 通过引用设置结构中的字段

c# - 类型为 'Newtonsoft.Json.Linq.JObject' 的对象无法转换为类型

json - 调用API返回预期的JSONArray,找到JSONObject

javascript - JQuery 1.4.4 和数据表 1.7 不工作

go - 数据库返回空集时无效的内存地址或 nil 指针取消引用

c++ - 结构数组,其中包含数组。不会编译

php - JSON 到 MYSQL - JSON 响应格式是否正确 - 循环正确吗?

php - Laravel 填充数组元素的验证规则