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


GO Decoder用法及代码示例

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

解码器从输入流中读取和解码 JSON 值。

用法:

type Decoder struct {
    // contains filtered or unexported fields
}

例子:

此示例使用解码器来解码不同 JSON 值的流。

package main

import (
    "encoding/json"
    "fmt"
    "io"
    "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))
    for {
        var m Message
        if err := dec.Decode(&m); err == io.EOF {
            break
        } else if err != nil {
            log.Fatal(err)
        }
        fmt.Printf("%s: %s\n", m.Name, m.Text)
    }
}

输出:

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

相关用法


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