Golang中使用JSON的一些小技巧分享

2019-11-10 10:55:31于海丽

前言

有的时候上游传过来的字段是string类型的,但是我们却想用变成数字来使用。 本来用一个json:",string" 就可以支持了,如果不知道golang的这些小技巧,就要大费周章了。

参考文章: JSON and struct composition in Go

临时忽略struct字段

type User struct {
 Email string `json:"email"`
 Password string `json:"password"`
 // many more fields…
}

临时忽略掉Password字段

json.Marshal(struct {
 *User
 Password bool `json:"password,omitempty"`
}{
 User: user,
})

临时添加额外的字段

type User struct {
 Email string `json:"email"`
 Password string `json:"password"`
 // many more fields…
}

临时忽略掉Password字段,并且添加token字段

json.Marshal(struct {
 *User
 Token string `json:"token"`
 Password bool `json:"password,omitempty"`
}{
 User: user,
 Token: token,
})

临时粘合两个struct

type BlogPost struct {
 URL string `json:"url"`
 Title string `json:"title"`
}

type Analytics struct {
 Visitors int `json:"visitors"`
 PageViews int `json:"page_views"`
}

json.Marshal(struct{
 *BlogPost
 *Analytics
}{post, analytics})

一个json切分成两个struct

json.Unmarshal([]byte(`{
 "url": "attila@attilaolah.eu",
 "title": "Attila's Blog",
 "visitors": 6,
 "page_views": 14
}`), &struct {
 *BlogPost
 *Analytics
}{&post, &analytics})

临时改名struct的字段

type CacheItem struct {
 Key string `json:"key"`
 MaxAge int `json:"cacheAge"`
 Value Value `json:"cacheValue"`
}

json.Marshal(struct{
 *CacheItem

 // Omit bad keys
 OmitMaxAge omit `json:"cacheAge,omitempty"`
 OmitValue omit `json:"cacheValue,omitempty"`

 // Add nice keys
 MaxAge int `json:"max_age"`
 Value *Value `json:"value"`
}{
 CacheItem: item,

 // Set the int by value:
 MaxAge: item.MaxAge,

 // Set the nested struct by reference, avoid making a copy:
 Value: &item.Value,
})

用字符串传递数字

type TestObject struct {
 Field1 int `json:",string"`
}

这个对应的json是 {"Field1": "100"}

如果json是 {"Field1": 100} 则会报错

容忍字符串和数字互转

如果你使用的是jsoniter,可以启动模糊模式来支持 PHP 传递过来的 JSON。

import "github.com/json-iterator/go/extra"

extra.RegisterFuzzyDecoders()

这样就可以处理字符串和数字类型不对的问题了。比如

var val string
jsoniter.UnmarshalFromString(`100`, &val)

又比如

var val float32
jsoniter.UnmarshalFromString(`"1.23"`, &val)

容忍空数组作为对象

PHP另外一个令人崩溃的地方是,如果 PHP array是空的时候,序列化出来是[]。但是不为空的时候,序列化出来的是