[golang]將結構體方法序列化到JSON
在寫Restful API時,時常要序列化巢狀的資源,有時還需要定製序列化的欄位。傳統的方法只有進行結構體巢狀,然後還有將結構體轉成map,剔除掉不需要的欄位,比較繁瑣。而ofollow,noindex" target="_blank">jsonfn 使用物件方法的思路,簡化了這一流程。
一、序列化指定的欄位
import "github.com/liamylian/jsonfn" type Book struct { Idint Titlestring AuthorIdint } // 只序列化Id, Title // bytes = {"Id":1,"Title":"Jane Eyre"} bytes, _, := jsonfn.Marshal(Book{Id: 1, Title: "Jane Eyre", AuthorId: 2}, "Id", "Title") // 序列化所有欄位 // bytes = {"AuthorId":2,Id":1,"Title":"Jane Eyre"} bytes, _, := jsonfn.Marshal(Book{Id: 1, Title: "Jane Eyre", AuthorId: 2}) bytes, _, := jsonfn.Marshal(Book{Id: 1, Title: "Jane Eyre", AuthorId: 2}, "*")
二、序列化巢狀資源
通過給Book和Author,分別新增Author和Country方法,可以在序列化Book時巢狀Author,而Author又嵌套了Country。
import ( "github.com/liamylian/jsonfn" "strconv" "time" ) type Book struct { Idint Titlestring AuthorIdint CreatedAt time.Time } func (b Book) Author() Author { return Author{ Id:b.AuthorId, Name: "author" + strconv.Itoa(b.AuthorId), } } type Author struct { Idint Namestring CountryId int } func (a Author) Country() Country { return Country{ Id:a.CountryId, Name: "country" + strconv.Itoa(a.CountryId), } } type Country struct { Idint Name string } func main() { book := Book{ Id:1, Title:"Jane Eyre", AuthorId:2, CreatedAt: time.Now(), } // output: // // { //"Id": 1, //"Title": "Jane Eyre", //"Author": { //"Id": 2, //"Name": "author2" //"Country": { //"Id": 0, //"Name": "country0" //} //} //} jsonStr, _ := jsonfn.Marshal(book, "Id", "Title", "Author{Id,Name}", "Author:Country{}") fmt.Println("%s", jsonStr) }