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
數據最后填充變量的操作。