使用golang中的json.Decoder解码顶级JSON数组

Rus*_*tam 3 json go unmarshalling json-deserialization

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

或者阅读整个JSON和json.Unmarshall是这种情况下唯一的方法吗?

我已经阅读了这个问题中接受的答案,并且无法弄清楚如何将它与顶级JSON数组一起使用

May*_*tel 6

您以与任何其他json相同的方式使用json.Decoder.唯一的区别是,不是解码成结构,而是需要在struct数组中解码json.这是一个非常简单的例子.去游乐场

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)
}
Run Code Online (Sandbox Code Playgroud)