当前位置: 首页>>编程示例 >>用法及示例精选 >>正文


GO Decoder.Decode用法及代码示例

GO语言"encoding/json"包中"Decoder.Decode"类型的用法及代码示例。

用法:

func(dec *Decoder) Decode(v any) error

Decode 从其输入中读取下一个JSON-encoded 值并将其存储在 v 指向的值中。

有关将 JSON 转换为 Go 值的详细信息,请参阅 Unmarshal 的文档。

示例(流):

此示例使用解码器对 JSON 对象的流式数组进行解码。

package main

import (
    "encoding/json"
    "fmt"
    "log"
    "strings"
)

func main() {
    const jsonStream = `
    [
        {"Name": "Ed", "Text": "Knock knock."},
        {"Name": "Sam", "Text": "Who's there?"},
        {"Name": "Ed", "Text": "Go fmt."},
        {"Name": "Sam", "Text": "Go fmt who?"},
        {"Name": "Ed", "Text": "Go fmt yourself!"}
    ]
`
    type Message struct {
        Name, Text string
    }
    dec := json.NewDecoder(strings.NewReader(jsonStream))

    // read open bracket
    t, err := dec.Token()
    if err != nil {
        log.Fatal(err)
    }
    fmt.Printf("%T: %v\n", t, t)

    // while the array contains values
    for dec.More() {
        var m Message
        // decode an array value (Message)
        err := dec.Decode(&m)
        if err != nil {
            log.Fatal(err)
        }

        fmt.Printf("%v: %v\n", m.Name, m.Text)
    }

    // read closing bracket
    t, err = dec.Token()
    if err != nil {
        log.Fatal(err)
    }
    fmt.Printf("%T: %v\n", t, t)

}

输出:

json.Delim: [
Ed: Knock knock.
Sam: Who's there?
Ed: Go fmt.
Sam: Go fmt who?
Ed: Go fmt yourself!
json.Delim: ]

相关用法


注:本文由纯净天空筛选整理自golang.google.cn大神的英文原创作品 Decoder.Decode。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。