Go JSON 的序列化和反序列化
Go JSON About 2,449 words序列化
json.Marshal
结构体
Go
设定结构体字段小写为不可导出,无法序列化不可导出字段。大写字段导出后JSON
字符串也将大写,故使用struct tag
添加标注json
自定义JSON
字段名。
type Result struct {
Code int `json:"code"`
Msg string `json:"msg"`
Data interface{} `json:"data"`
}
func main() {
result := &Result{0, "请求成功", "this is data"}
resultStr, _ := json.Marshal(result)
// {"code":0,"msg":"请求成功","data":"this is data"}
fmt.Printf("Result JSON format: %s\n", resultStr)
}
map
func main() {
m := make(map[string]interface{})
m["id"] = 1
m["price"] = 10.24
m["vip"] = true
m["create_ts"] = "2020-10-28"
m["remark"] = nil
mapStr, _ := json.Marshal(m)
// {"create_ts":"2020-10-28","id":1,"price":10.24,"remark":null,"vip":true}
fmt.Printf("Map JSON format: %s\n", mapStr)
}
反序列化
json.Unmarshal
结构体
type Address struct {
Type string
City string
Country string
}
func main() {
addressJsonStr := `{"Type":"CN","City":"Shanghai","Country":"China"}`
var address Address
err = json.Unmarshal([]byte(addressJsonStr), &address)
if err != nil {
log.Println(err)
}
// {CN Shanghai China}
fmt.Println(address)
}
map
func main() {
addressJsonStr := `{"Type":"CN","City":"Shanghai","Country":"China"}`
m2 := make(map[string]interface{})
err = json.Unmarshal([]byte(addressJsonStr), &m2)
// map[City:Shanghai Country:China Type:CN]
fmt.Println(m2)
}
json.NewDecoder
json.NewDecoder
接收一个io.Reader
参数,对于大批量的JSON
字符串,它分批加载处理,故比json.Unmarshal
性能更佳。
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!"}
]
`
var i []map[string]interface{}
decoder := json.NewDecoder(strings.NewReader(jsonStream))
err = decoder.Decode(&i)
if err != nil {
log.Fatal(err)
}
fmt.Println(i)
}
在HTTP
服务的POST
请求中,可以用来直接反序列化前端传上来的JSON
字符串。
type User struct {
Name string
Age int
}
// json.NewDecoder(r.Body)
func HandleUse(w http.ResponseWriter, r *http.Request) {
defer r.Body.Close()
var u User
if err := json.NewDecoder(r.Body).Decode(&u); err != nil {
w.WriteHeader(http.StatusBadRequest)
return
}
w.WriteHeader(http.StatusOK)
_, _ = fmt.Fprintf(w, "姓名:%s,年龄:%d", u.Name, u.Age)
}
Views: 4,892 · Posted: 2020-11-02
————        END        ————
Give me a Star, Thanks:)
https://github.com/fendoudebb/LiteNote扫描下方二维码关注公众号和小程序↓↓↓
Loading...