dsvtnz6350
2014-02-23 14:34
浏览 887
已采纳

将请求中的json转换为golang中的数组

How can I convert a json array to an array of structs? Example:

[
  {"name": "Rob"},
  {"name": "John"}
]

I'm retrieving the json from a request:

body, err := ioutil.ReadAll(r.Body)

How would I unmarshal this into an array?

图片转代码服务由CSDN问答提供 功能建议

如何将json数组转换为结构数组? 示例:

  [
 {“ name”:“ Rob”},
 {“ name”:“ John”} 
] 
  <  / pre> 
 
 

我正在从请求中检索json:

  body,err:= ioutil.ReadAll(r.Body)
 <  / code>  
 
 

如何将其解组为数组?

  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • dpj83664 2014-02-23 15:47
    已采纳

    you simply use json.Unmarshal for this. Example:

    import "encoding/json"
    
    
    // This is the type we define for deserialization.
    // You can use map[string]string as well
    type User struct {
    
        // The `json` struct tag maps between the json name
        // and actual name of the field
        Name string `json:"name"`
    }
    
    // This functions accepts a byte array containing a JSON
    func parseUsers(jsonBuffer []byte) ([]User, error) {
    
        // We create an empty array
        users := []User{}
    
        // Unmarshal the json into it. this will use the struct tag
        err := json.Unmarshal(jsonBuffer, &users)
        if err != nil {
            return nil, err
        }
    
        // the array is now filled with users
        return users, nil
    
    }
    
    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题