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

栏目: Go · 发布时间: 5年前

内容简介:在写Restful API时,时常要序列化嵌套的资源,有时还需要定制序列化的字段。传统的方法只有进行结构体嵌套,然后还有将结构体转成map,剔除掉不需要的字段,比较繁琐。而二、序列化嵌套资源通过给Book和Author,分别添加Author和Country方法,可以在序列化Book时嵌套Author,而Author又嵌套了Country。

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

一、序列化指定的字段

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

二、序列化嵌套资源

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

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)
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Objective-C编程

Objective-C编程

[美] Aaron Hillegass / 夏伟频、李骏 / 华中科技大学出版社 / 2012-9-25 / 58.00元

《Objective-C编程》讲述Objective-C编程语言和基本的iOS/Mac开发知识。作者首先从基本的编程概念讲起(变量、条件语句、循环结构等),接着用浅显易懂的语言讲解Objective-C和Foundation的知识,包括Objective-C的基本语法、 Foundation常用类 、内存管理、常用设计模式等,最后手把手教读者编写完整的、基于事件驱动的iOS/Mac应用。作者还穿插......一起来看看 《Objective-C编程》 这本书的介绍吧!

RGB转16进制工具
RGB转16进制工具

RGB HEX 互转工具

MD5 加密
MD5 加密

MD5 加密工具

UNIX 时间戳转换
UNIX 时间戳转换

UNIX 时间戳转换