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: ]
相關用法
- GO Decoder.Token用法及代碼示例
- GO Decoder用法及代碼示例
- GO DecodeLastRuneInString用法及代碼示例
- GO DecodeRuneInString用法及代碼示例
- GO DecodeRune用法及代碼示例
- GO Decode用法及代碼示例
- GO DecodeLastRune用法及代碼示例
- GO DecodeString用法及代碼示例
- GO DumpResponse用法及代碼示例
- GO DB.QueryRowContext用法及代碼示例
- GO Date用法及代碼示例
- GO DB.ExecContext用法及代碼示例
- GO Dial用法及代碼示例
- GO DB.BeginTx用法及代碼示例
- GO DumpRequest用法及代碼示例
- GO Drawer用法及代碼示例
- GO Duration.Hours用法及代碼示例
- GO Duration.Round用法及代碼示例
- GO DumpRequestOut用法及代碼示例
- GO Duration用法及代碼示例
注:本文由純淨天空篩選整理自golang.google.cn大神的英文原創作品 Decoder.Decode。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。