golang 中把struct 转成json格式输出

  1. package main
  2.  
  3. import (
  4. "encoding/json"
  5. "fmt"
  6. )
  7.  
  8. type Person struct {
  9. Name string `json:"name,omitempty"`
  10. DoB string `json:"dob,omitempty"`
  11. Age string `json:"-,omitempty"`
  12. }
  13.  
  14. type Singer struct {
  15. Person
  16. MusicGenre string `json:"music_genre,omitempty"`
  17. Age string `json:"ageee,omitempty"`
  18. }
  19.  
  20. func ToJSON(s interface{}) (string, error) {
  21. bs, err := json.Marshal(s)
  22. if err != nil {
  23. return "", err
  24. }
  25. // fmt.Println(bs)
  26. return string(bs), nil
  27. }
  28.  
  29. func main() {
  30. s := Singer{
  31. Person{"John Singer",
  32. "01-02-1975",
  33. "13"},
  34. "pop", "12" }
  35. sJSON, _ := ToJSON(s)
  36. fmt.Println(sJSON)
  37. // {"name":"John Singer","dob":"01-02-1975","music_genre":"pop"}
  38. }

  

---------------------------------

One of the things that I missed the most, apart from generics, when coming to Go while having Java background was the lack of inheritance. In JVM it was pretty simple, as you can define a parent and child classes, then have a common behavior present all the children objects. This is not the case in Go, and I had to learn how to work around this. Here, we don't have inheritance, we have the composition, and for that, we have a pretty useful technique called embedding structs.

Manual composition vs embedding

In the classical approach to composition, we add what we'd call a parent class as another field in the child one. In Go terms, we should first define a parent struct with common attributes:

  1. type Person struct {
  2. Name string
  3. }

Then we should add an attribute of type Person to another struct which we want to use that common features from the parent:

  1. type Singer struct {
  2. Parent Person
  3. MusicGenre string
  4. }

This may not seem like a huge improvement, but we can use a shorter notation and embedPerson into Singer by skipping the attribute name and just leave its type:

  1. type Singer struct {
  2. Person
  3. MusicGenre string
  4. }

In both cases, when creating an instance of Singer inline we need to specify a definition of parent struct with its name - when embedding it is the name of that struct:

  1. // manual composition
  2. s0 := embedding.Singer{
  3. Parent: embedding.Person{Name: "John Singer"},
  4. MusicGenre: "pop",
  5. }
  6. // embedding
  7. s1 := embedding.Singer{
  8. Person: embedding.Person{Name: "John Singer"},
  9. MusicGenre: "pop",
  10. }

The difference is larger than just saving a few characters in the struct definition. First of all, when doing it manually we'd have to use attribute name (Parent) all the time:

  1. // manual composition
  2. fmt.Println(s0.Parent.Name)

While with embedding we can (but don't have to) refer to the attributes of the embedded struct as if they were defined in the child:

  1. // embedding
  2. fmt.Println(s1.Parent.Name)
  3. fmt.Println(s1.Name)

Another interesting thing is that if we want to build a Singer struct by adding attributes to an empty instance, again we get a feeling of the inheritance:

  1. // manual composition
  2. s0 := embedding.Singer{MusicGenre: "pop"}
  3. s0.Parent.Name = "John Singer" // we have to do this explicitly
  4. fmt.Println(s0.Parent.Name)
  5. // embedding
  6. s1 := embedding.Singer{MusicGenre: "pop"}
  7. // we can be explicit with
  8. // s1.Person.Name = "John Doe"
  9. // but we can as well do this:
  10. s1.Name = "John Singer"
  11. fmt.Println(s1.Parent.Name)

Calling inherited functions

Another useful feature of embedding structs is that we can call parent's functions that were inherited as if they were defined on a child struct. For example, we can add a Talk(..)function on Person and use it on an instance of Singer:

  1. type Person struct {
  2. ...
  3. }
  4. func (p Person) Talk(message string) {
  5. fmt.Printf("%s (a person) says \"%s\"\n", p.Name, message)
  6. }
  7. func main() {
  8. s := Singer{}
  9. s.Name = "John Doe"
  10. s.Talk("Hello, reader!")
  11. // John Doe (a person) says "Hello, reader!"
  12. }

Awesome! Remember that the attributes and function are promoted to the child struct only if they are not overwritten there. If we define a Talk(..) function directly on Singer, the one from Person would never be called:

  1. ...
  2. func (p Singer) Talk(message string) {
  3. fmt.Printf("Singer %s says \"%s\"\n", p.Name, message)
  4. }
  5. func main() {
  6. s := Singer{}
  7. s.Name = "John Doe"
  8. s.Talk("Hello, again!")
  9. // Singer John Singer says "Hello again!"
  10. }

The trick is when a function that is promoted calls another one. For example, if we define a Type() function that would return the struct identifier on both Person and Singer, then call it within Talk function that would be promoted from the parent, we would get the Type() from the parent as well. The reason for this is that at the time of executing the function, Go does not realize we are dealing with some inheritance stuff and we don't go back to the original caller to see what the context is:

  1. func (p Person) Type() string {
  2. return "PERSON"
  3. }
  4. func (p Person) Talk(message string) {
  5. fmt.Printf("%s (type=%s) says \"%s\"\n", p.Name, p.Type(), message)
  6. }
  7. ...
  8. func (s Singer) Type() string {
  9. return "SINGER"
  10. }
  11. func (s Singer) Sing(title string) {
  12. fmt.Printf("%s (type=%s) sings %s in the style of %s.\n", s.Name, s.Type(), title, s.MusicGenre)
  13. }
  14. ...
  15. func main() {
  16. s := Singer{MusicGenre: "rock"}
  17. s.Name = "Johny Singerra"
  18. s.Sing("Welcome to the forest")
  19. // Johny Singerra (type=SINGER) sings Welcome to the forest in the style of rock.
  20. s.Talk("Hello!")
  21. // Johny Singerra (type=PERSON) says "Hello!"
  22. }

Hiding JSON properties

Another interesting fact is the way Go handler JSON tags that can identify attributes of a struct. For example, we can marshal Singer to JSON and see that both its own and the inherited properties end up in the document:

  1. type Person struct {
  2. Name string `json:"name,omitempty"`
  3. DoB string `json:"dob,omitempty"`
  4. }
  5. ...
  6. type Singer struct {
  7. Person
  8. MusicGenre string `json:"music_genre,omitempty"`
  9. }
  10. ...
  11. func (s Singer) ToJSON() (string, error) {
  12. bs, err := json.Marshal(s)
  13. if err != nil {
  14. return "", err
  15. }
  16. return string(bs), nil
  17. }
  18. ...
  19. func main() {
  20. s := embedding.Singer{
  21. Person: embedding.Person{
  22. Name: "John Singer",
  23. DoB: "01-02-1975",
  24. },
  25. MusicGenre: "pop",
  26. }
  27. sJSON, _ := s.ToJSON()
  28. fmt.Println(sJSON)
  29. // {"name":"John Singer","dob":"01-02-1975","music_genre":"pop"}
  30. }

It's great that both name and dob properties are there, but what if we want to hide some of those for JSON marshaler? Let's create a MusicStar struct where we'll add a nickname to the Singer, but at the same time we'd like to hide the date of birth (since we want to keep it as a secret):

  1. type MusicStar struct {
  2. Singer
  3. Nickname string `json:"nickname,omitempty"`
  4. DoB string `json:"-,omitempty"`
  5. }
  6. func (ms MusicStar) ToJSON() (string, error) {
  7. bs, err := json.Marshal(ms)
  8. if err != nil {
  9. return "", err
  10. }
  11. return string(bs), nil
  12. }

Note that we've added a DoB field but added a - as JSON tag to indicate that this field should be removed from marshaling. Unfortunately, that doesn't work:

  1. func main() {
  2. ms := embedding.MusicStar{
  3. Nickname: "Starry",
  4. Singer: embedding.Singer{
  5. Person: embedding.Person{
  6. Name: "Joe Star",
  7. DoB: "01-02-1975",
  8. },
  9. MusicGenre: "pop",
  10. },
  11. }
  12. msJSON, _ := ms.ToJSON()
  13. fmt.Println(msJSON)
  14. // "name":"Joe Star","dob":"01-02-1975","music_genre":"pop","nickname":"Starry"}
  15. }

That is because although Go sees our - JSON tag, it recognizes it as undefined and go deeper into embedded structs to see if there is a field that matches the name, but has some concrete tag defined. It finds one, so that is being used. We can, however, trick the language into hiding that nested DoB, by defining the same property with the same JSON tag in the top-level struct. This way the DoB from Person will never be promoted to the top level JSON object, since its top-level value is empty, therefore the empty string overwrites anything that comes from Person:

  1. type MusicStar struct {
  2. Singer
  3. Nickname string `json:"nickname,omitempty"`
  4. DoB string `json:"dob,omitempty"`
  5. }
  6. ...
  7. msJSON, _ := ms.ToJSON()
  8. fmt.Println(msJSON)
  9. // {"name":"Joe Star","music_genre":"pop","nickname":"Starry"}

As you can see, embedded structs solve some of the things we would achieve via classical inheritance, but it's necessary to understand how it works to avoid unexpected behaviors and gotchas. The full source code of these examples is available on Github.

golang embedded structs的更多相关文章

  1. 从OOP的角度看Golang

    资料来源 https://github.com/luciotato/golang-notes/blob/master/OOP.md?hmsr=toutiao.io&utm_medium=tou ...

  2. golang Methods on structs

    原文:http://golangtutorials.blogspot.com/2011/06/methods-on-structs.html snmp 下载,有空学习一下! https://sourc ...

  3. Go语言(golang)开源项目大全

    转http://www.open-open.com/lib/view/open1396063913278.html内容目录Astronomy构建工具缓存云计算命令行选项解析器命令行工具压缩配置文件解析 ...

  4. [转]Go语言(golang)开源项目大全

    内容目录 Astronomy 构建工具 缓存 云计算 命令行选项解析器 命令行工具 压缩 配置文件解析器 控制台用户界面 加密 数据处理 数据结构 数据库和存储 开发工具 分布式/网格计算 文档 编辑 ...

  5. Golang优秀开源项目汇总, 10大流行Go语言开源项目, golang 开源项目全集(golang/go/wiki/Projects), GitHub上优秀的Go开源项目

    Golang优秀开源项目汇总(持续更新...)我把这个汇总放在github上了, 后面更新也会在github上更新. https://github.com/hackstoic/golang-open- ...

  6. golang sync.noCopy 类型 —— 初探 copylocks 与 empty struct

    问题引入 学习golang(v1.16)的 WaitGroup 代码时,看到了一处奇怪的用法,见下方类型定义: type WaitGroup struct { noCopy noCopy ... } ...

  7. Golang通脉之面向对象

    面向对象的三大特征: 封装:隐藏对象的属性和实现细节,仅对外提供公共访问方式 继承:使得子类具有父类的属性和方法或者重新定义.追加属性和方法等 多态:不同对象中同种行为的不同实现方式 Go并不是一个纯 ...

  8. 【转载】关于Embedded Linux启动的经典问题

    转载自:http://linux.chinaunix.net/techdoc/install/2009/04/13/1107608.shtml 发信人: armlinux (armlinux), 信区 ...

  9. [转]50 Shades of Go: Traps, Gotchas, and Common Mistakes for New Golang Devs

    http://devs.cloudimmunity.com/gotchas-and-common-mistakes-in-go-golang/ 50 Shades of Go: Traps, Gotc ...

随机推荐

  1. Note 1: Good

    Note 1: Good 1. The collection of Linkun's [1]: 1.1coolJoy says "cool" when he heard that ...

  2. php redis mysql apache 下载地址

    Mysql:https://dev.mysql.com/get/Downloads/MySQL-5.6/mysql-5.6.36-linux-glibc2.5-x86_64.tar.gz php:ht ...

  3. elasticsearch备份脚本

    1.主要文件 [root@k8s elasticsearch]# tree . ├── backup_es.sh ├── indices_file.txt ├── recover_es.sh └── ...

  4. UWP笔记-消息弹窗自动淡出

    为了让用户有个更好的UI交互,可以增加自动淡出的消息弹窗,例如:网易云音乐UWP,切换播放模式时,出现的类似消息提示. 右键项目,添加用户控件 UserControlDemo.xaml: <Us ...

  5. python 复制

    1. list的复制 直接用赋值符号实现浅复制,两者用id()函数的返回值是相同的,也就是占用同一块内存空间. 导入 copy 库, 用 copy.deepcopy(list1) 再赋值实现深复制,两 ...

  6. IDEA插件之alibaba编程规范

    1.做什么 这是阿里巴巴的编码规范插件,规范内容可以查阅 https://github.com/alibaba/p3c/blob/master/阿里巴巴Java开发手册(华山版).pdf 2.File ...

  7. redis单机连接池

    一.配置文件 1. db.properties配置文件#IP地址 redis.ip = 127.0.0.1 #端口号 redis.port= #最大连接数 redis.max.total= #最大空闲 ...

  8. Photon Server 实现注册与登录(五) --- 服务端、客户端完整代码

    客户端代码:https://github.com/fotocj007/PhotonDemo_Client 服务端代码:https://github.com/fotocj007/PhotonDemo_s ...

  9. python colormap

    from colormap import rgb2hex import numpy as np from matplotlib import pyplot as plt color_names = [ ...

  10. OpsManager管理MongoDB

    mydb1 Ops Manager,mongodb,agent mydb2 mongodb,agent mydb3 mongodb,agent NUMA Settings sysctl -w vm.z ...