Golang json用法详解(一)
本文内容纲要:
-Golangjson用法详解(一)
-简介
-Golang解析JSON之Tag篇
Golangjson用法详解(一)
简介
json格式可以算我们日常最常用的序列化格式之一了,Go语言作为一个由Google开发,号称互联网的C语言的语言,自然也对JSON格式支持很好。但是Go语言是个强类型语言,对格式要求极其严格而JSON格式虽然也有类型,但是并不稳定,Go语言在解析来源为非强类型语言时比如PHP等序列化的JSON时,经常遇到一些问题诸如字段类型变化导致无法正常解析的情况,导致服务不稳定。所以本篇的主要目的
- 就是挖掘Golang解析json的绝大部分能力
- 比较优雅的解决解析json时存在的各种问题
- 深入一下Golang解析json的过程
Golang解析JSON之Tag篇
-
一个结构体正常序列化过后是什么样的呢?
packagemain import( "encoding/json" "fmt" ) //Product商品信息 typeProductstruct{ Namestring ProductIDint64 Numberint Pricefloat64 IsOnSalebool } funcmain(){ p:=&Product{} p.Name="Xiaomi6" p.IsOnSale=true p.Number=10000 p.Price=2499.00 p.ProductID=1 data,_:=json.Marshal(p) fmt.Println(string(data)) } //结果 {"Name":"Xiaomi6","ProductID":1,"Number":10000,"Price":2499,"IsOnSale":true}
-
何为Tag,tag就是标签,给结构体的每个字段打上一个标签,标签冒号前是类型,后面是标签名。
//Product_ typeProductstruct{ Namestring`json:"name"` ProductIDint64`json:"-"`//表示不进行序列化 Numberint`json:"number"` Pricefloat64`json:"price"` IsOnSalebool`json:"is_on_sale,string"` } //序列化过后,可以看见 {"name":"Xiaomi6","number":10000,"price":2499,"is_on_sale":"false"}
-
omitempty,tag里面加上omitempy,可以在序列化的时候忽略0值或者空值
packagemain import( "encoding/json" "fmt" ) //Product_ typeProductstruct{ Namestring`json:"name"` ProductIDint64`json:"product_id,omitempty"` Numberint`json:"number"` Pricefloat64`json:"price"` IsOnSalebool`json:"is_on_sale,omitempty"` } funcmain(){ p:=&Product{} p.Name="Xiaomi6" p.IsOnSale=false p.Number=10000 p.Price=2499.00 p.ProductID=0 data,_:=json.Marshal(p) fmt.Println(string(data)) } //结果 {"name":"Xiaomi6","number":10000,"price":2499}
-
type,有些时候,我们在序列化或者反序列化的时候,可能结构体类型和需要的类型不一致,这个时候可以指定,支持string,number和boolean
packagemain import( "encoding/json" "fmt" ) //Product_ typeProductstruct{ Namestring`json:"name"` ProductIDint64`json:"product_id,string"` Numberint`json:"number,string"` Pricefloat64`json:"price,string"` IsOnSalebool`json:"is_on_sale,string"` } funcmain(){ vardata=`{"name":"Xiaomi6","product_id":"10","number":"10000","price":"2499","is_on_sale":"true"}` p:=&Product{} err:=json.Unmarshal([]byte(data),p) fmt.Println(err) fmt.Println(*p) } //结果 <nil> {Xiaomi610100002499true}
本文内容总结:Golangjson用法详解(一),简介,Golang解析JSON之Tag篇,
原文链接:https://www.cnblogs.com/yangshiyu/p/6942414.html