dongmei2351
2016-08-02 09:10
浏览 392

在Golang中使用json.Decoder解码顶级JSON数组

Is it possible to decode top level JSON array with json.Decoder?

Or reading entire JSON and json.Unmarshall is the only way in this case?

I have read the accepted answer in this question and cannot figure out how to use it with top level JSON array

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

是否可以使用json.Decoder解码顶级JSON数组?

或读取整个JSON和json。在这种情况下,唯一的方法是Unmarshall吗?

我已经阅读了这个问题,无法弄清楚如何将其与顶级JSON数组一起使用

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • duanliangman5398 2016-08-02 10:04
    已采纳

    You use json.Decoder in same way as any other json. Only difference is that instead of decoding into a struct, json need to be decoded in array of struct. This is a very simple example. Go Playground

    package main
    
    import (
        "bytes"
        "encoding/json"
        "fmt"
    )
    
    type Result struct {
        Name         string `json:"Name"`
        Age          int    `json:"Age`
        OriginalName string `json:"Original_Name"`
    }
    
    func main() {
        jsonString := `[{"Name":"Jame","Age":6,"Original_Name":"Jameson"}]`
        result := make([]Result, 0)
        decoder := json.NewDecoder(bytes.NewBufferString(jsonString))
        err := decoder.Decode(&result)
        if err != nil {
            panic(err)
        }
        fmt.Println(result)
    }
    
    点赞 评论
  • douwen3362 2016-08-02 10:03

    https://play.golang.org/p/y2sKN7e8gf

    Note that use of var r interface{} is not recommended, you should define your JSON structure as a Go struct to parse it correctly.

    点赞 评论

相关推荐 更多相似问题