Skip to content

Instantly share code, notes, and snippets.

@xigang
Created March 10, 2016 06:46
Show Gist options
  • Save xigang/a725723b1ecfb4888d40 to your computer and use it in GitHub Desktop.
Save xigang/a725723b1ecfb4888d40 to your computer and use it in GitHub Desktop.
使用encoding/json包反序列化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
}
//func NewDecoder(r io.Reader) *Decoder
//NewDecoder 主要给r创建一个decoder对象
dec := json.NewDecoder(strings.NewReader(jsonStream))
for {
var m Message
//Decode 反序列化一个JSON编码的数据,并将结果存储到一个指向v的指针
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!
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment