當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


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。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。