Java golang序列化_[golang]将结构体方法序列化到JSON

在写Restful API时,时常要序列化嵌套的资源,有时还需要定制序列化的字段。传统的方法只有进行结构体嵌套,然后还有将结构体转成map,剔除掉不需要的字段,比较繁琐。而jsonfn使用对象方法的思路,简化了这一流程。

一、序列化指定的字段

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}, "*")

二、序列化嵌套资源

通过给Book和Author,分别添加Author和Country方法,可以在序列化Book时嵌套Author,而Author又嵌套了Country。

import (

"github.com/study-only/jsonfn"

"strconv"

"time"

)

type Book struct {

Id int

Title string

AuthorId int

CreatedAt time.Time

}

func (b Book) Author() Author {

return Author{

Id: b.AuthorId,

Name: "author" + strconv.Itoa(b.AuthorId),

}

}

type Author struct {

Id int

Name string

CountryId int

}

func (a Author) Country() Country {

return Country{

Id: a.CountryId,

Name: "country" + strconv.Itoa(a.CountryId),

}

}

type Country struct {

Id int

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)

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值