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数据最后填充变量的操作。

相关文章:

  • 2021-09-02
  • 2022-01-05
  • 2021-05-31
  • 2021-10-23
  • 2021-08-13
  • 2021-08-01
猜你喜欢
  • 2022-02-19
  • 2022-12-23
  • 2021-11-30
  • 2021-05-24
  • 2022-12-23
  • 2022-01-23
  • 2021-06-22
相关资源
相似解决方案