[golang]將結構體方法序列化到JSON

在寫Restful API時,時常要序列化嵌套的資源,有時還須要定製序列化的字段。傳統的方法只有進行結構體嵌套,而後還有將結構體轉成map,剔除掉不須要的字段,比較繁瑣。而jsonfn使用對象方法的思路,簡化了這一流程。git

1、序列化指定的字段github

import "github.com/liamylian/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}, "*")

2、序列化嵌套資源
經過給Book和Author,分別添加Author和Country方法,能夠在序列化Book時嵌套Author,而Author又嵌套了Country。json

import (
    "github.com/liamylian/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)
}
相關文章
相關標籤/搜索