你们好,我叫谢伟,是一名程序员。程序员
近期我会持续更新内置库的学习笔记,主要参考的是文档 godoc 和 内置库的源码json
在平常开发过程当中,使用最频繁的固然是内置库,无数的开源项目,无不是在内置库的基础之上进行衍生、开发,因此实际上是有很大的必要进行梳理学习。segmentfault
本节的主题:内置库 jsonbash
大纲:性能
既然是 json 操做,那么核心应该是包括两个方面:学习
对应的方法:ui
func Marshal(v interface{}) ([]byte, error)this
func MarshalIndent(v interface{}, prefix, indent string) ([]byte, error)spa
func Unmarshal(data []byte, v interface{}) errorcode
具体如何使用呢?
布尔类型
func boolToJson(ok bool) []byte {
jsonResult, _ := json.Marshal(ok)
return jsonResult
}
func jsonToBool(value []byte) bool {
var goResult bool
json.Unmarshal(value, &goResult)
return goResult
}
func main(){
fmt.Println(string(boolToJson(1 == 1)))
fmt.Println(jsonToBool([]byte(`true`)))
}
>>
true
true
复制代码
数值型
func intToJson(value int) []byte {
jsonInt, _ := json.Marshal(value)
return jsonInt
}
func main(){
fmt.Println(string(intToJson(12)))
}
>>
12
复制代码
结构体
结构体 转换为 json
type Info struct {
Name string `json:"name,omitempty"`
Age int `json:"age,string"`
City string `json:"city_shanghai"`
Company string `json:"-"`
}
func (i Info) MarshalOp() []byte {
jsonResult, _ := json.Marshal(i)
return jsonResult
}
func main(){
var info Info
info = Info{
Name: "XieWei",
Age: 100,
City: "shangHai",
Company: "Only Me",
}
fmt.Println(string(info.MarshalOp()))
var otherInfo Info
otherInfo.Name = ""
otherInfo.Age = 20
otherInfo.City = "BeiJing"
otherInfo.Company = "Only You"
fmt.Println(string(otherInfo.MarshalOp()))
}
>>
{"name":"XieWei","age":"100","city_shanghai":"shangHai"}
{"age":"20","city_shanghai":"BeiJing"}
复制代码
还记得咱们之间讲的 反射章节 结构体的 tag 吗?
-
表示忽略该字段json 转换为 结构体:
func UnMarshalExample(value []byte) (result Info) {
json.Unmarshal(value, &result)
return result
}
func main(){
fmt.Println(UnMarshalExample([]byte(`{"name":"xieWei", "age": "20", "city_shanghai": "GuangDong"}`)))
}
>>
{xieWei 20 GuangDong }
复制代码
好,至此,咱们经常使用的 json 操做就这些,主要两个方面:Marshal 和 UnMarshal
大概讲述了下 结构体的 tag 的做用:
列举几个再经常使用的:
Valid
判断是不是有效的 json 格式的数据
func main(){
fmt.Println(json.Valid([]byte(`{"name":1, 2}`)))
}
>>
false
复制代码
Marshaler 接口,须要实现 MarshalJSON 方法
自定义序列化返回值
type Marshaler interface {
MarshalJSON() ([]byte, error)
}
复制代码
type SelfMarshal struct {
Name string
Age int
City string
}
func (self SelfMarshal) MarshalJSON() ([]byte, error) {
result := fmt.Sprintf("name:--%s,age:--%d,city:--%s", self.Name, self.Age, self.City)
if !json.Valid([]byte(result)) {
fmt.Println("invalid")
return json.Marshal(result)
}
return []byte(result), nil
}
func main(){
var self = SelfMarshal{}
self.Age = 20
self.Name = "XieWei"
self.City = "HangZhou"
selfJsonMarshal, err := json.Marshal(self)
fmt.Println(err, string(selfJsonMarshal))
}
>>
<nil> "name:--XieWei,age:--20,city:--HangZhou"
复制代码
type jsonTime time.Time
//实现它的json序列化方法
func (this jsonTime) MarshalJSON() ([]byte, error) {
var stamp = fmt.Sprintf("\"%s\"", time.Time(this).Format("2006-01-02 15:04:05"))
return []byte(stamp), nil
}
type Test struct {
Date jsonTime `json:"date"`
Name string `json:"name"`
State bool `json:"state"`
}
func main(){
var t = Test{}
t.Date = jsonTime(time.Now())
t.Name = "Hello World"
t.State = true
body, _ := json.Marshal(t)
fmt.Println(string(body))
}
>>
{"date":"2018-11-06 22:23:19","name":"Hello World","state":true}
复制代码
各 json 解析库性能比对 | 各 json 解析库性能比对
收获:
func (self SelfMarshal) MarshalJSON() ([]byte, error) {
result := fmt.Sprintf("name:--%s,age:--%d,city:--%s", self.Name, self.Age, self.City)
return []byte(result), nil
}
复制代码
上文代码会报错,为何?由于不是标准 json 格式的数据。
因此一般建议这么作:
func (self SelfMarshal) MarshalJSON() ([]byte, error) {
result := fmt.Sprintf("name:--%s,age:--%d,city:--%s", self.Name, self.Age, self.City)
if !json.Valid([]byte(result)) {
fmt.Println("invalid")
return json.Marshal(result)
}
return []byte(result), nil
}
复制代码
即将字符串 marshal 处理。
<完>