go 用 Decoder解析数据流
func ExampleDecoder() {
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)
}
// Output:
// Ed: Knock knock.
// Sam: Who's there?
// Ed: Go fmt.
// Sam: Go fmt who?
// Ed: Go fmt yourself!
}
如果JSON数据的载体是打开的文件或者HTTP请求体这种数据流(他们都是io.Reader的实现),我们不必把JSON数据读取出来后再去调用encode/json包的UnMarshall方法,包提供的Decode方法可以完成读取数据流并解析JSON数据最后填充变量的操作。
small_lei_it 技术无止境,追求更高。

浙公网安备 33010602011771号