在写Restful API时,时常要序列化嵌套的资源,有时还需要定制序列化的字段。传统的方法只有进行结构体嵌套,然后还有将结构体转成map,剔除掉不需要的字段,比较繁琐。而jsonfn使用对象方法的思路,简化了这一流程。
一、序列化指定的字段
<pre><code>import "github.com/study-only/jsonfn" type Book struct { Id int Title string AuthorId int } // 只序列化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}, "*") </code></pre>二、序列化嵌套资源
通过给Book和Author,分别添加Author和Country方法,可以在序列化Book时嵌套Author,而Author又嵌套了Country。
您可能感兴趣的文章:
golang结构体tag的使用
[golang]将结构体方法序列化到JSON
Go 学习笔记 09 | Golang 结构体与 JSON 互相转换
golang json[]
Go基础及语法(四)
golang json忽略解析字段的两个方法 (golang json 序列化含有父节点指针的结构体时电脑跑满内存卡死)
Golang JSON-序列化map,切片(slice),结构体(struct)
golang反射reflect
Golang JSON-反序列化map,切片(slice),结构体(struct)
golang-json使用(json tag)