Golang 中 omitempty的作用
作者:? 发布时间:2024-04-25 15:13:03
标签:Golang,omitempty,作用
前言
在尝试将结构体序列化为 Json 时,你可能会遇到 “omitempty” 标记,本小记就来浅看一下它如何起作用。
先上结论:
基本类型的默认值会被 omit,除了数组。
指针类型为 nil 时会被 omit。
Talk is cheap. Show me the code.
package main
import (
"encoding/json"
"errors"
"fmt"
)
type TestNotOmitEmpty struct {
Uint8 uint8 `json:"uint8"`
Uint16 uint16 `json:"uint16"`
Uint32 uint32 `json:"uint32"`
Uint64 uint64 `json:"uint64"`
Int8 int8 `json:"int8"`
Int16 int16 `json:"int16"`
Int32 int32 `json:"int32"`
Int64 int64 `json:"int64"`
Int int `json:"int"`
Float32 float32 `json:"float32"`
Float64 float64 `json:"float64"`
// Complex64 complex64 `json:"complex64"` // json: unsupported type
// Complex128 complex128 `json:"complex128"` // json: unsupported type
Byte byte `json:"byte"`
Rune rune `json:"rune"`
Uintptr uintptr `json:"uintptr"`
String string `json:"string"`
StringPointer *string `json:"stringPointer"`
Array [10]int `json:"array"`
Slice []int `json:"slice"`
Map map[int]string `json:"map"`
// Channel chan int `json:"channel"` // json: unsupported type
Interface interface{} `json:"interface"`
Error error `json:"error"`
}
type TestOmitEmptyWithDefaultValue struct {
Uint8 uint8 `json:"uint8,omitempty"`
Uint16 uint16 `json:"uint16,omitempty"`
Uint32 uint32 `json:"uint32,omitempty"`
Uint64 uint64 `json:"uint64,omitempty"`
Int8 int8 `json:"int8,omitempty"`
Int16 int16 `json:"int16,omitempty"`
Int32 int32 `json:"int32,omitempty"`
Int64 int64 `json:"int64,omitempty"`
Int int `json:"int,omitempty"`
Float32 float32 `json:"float32,omitempty"`
Float64 float64 `json:"float64,omitempty"`
// Complex64 complex64 `json:"complex64,omitempty"` // json: unsupported type
// Complex128 complex128 `json:"complex128,omitempty"` // json: unsupported type
Byte byte `json:"byte,omitempty"`
Rune rune `json:"rune,omitempty"`
Uintptr uintptr `json:"uintptr,omitempty"`
String string `json:"string,omitempty"`
StringPointer *string `json:"stringPointer,omitempty"`
Array [10]int `json:"array,omitempty"`
Slice []int `json:"slice,omitempty"`
Map map[int]string `json:"map,omitempty"`
// Channel chan int `json:"channel,omitempty"` // json: unsupported type
Interface interface{} `json:"interface,omitempty"`
Error error `json:"error,omitempty"`
}
func ToStringPointer(s string) *string {
return &s
}
func main() {
testOmitEmpty := TestNotOmitEmpty{}
jsonData, err := json.Marshal(testOmitEmpty)
if err != nil {
println(err)
panic(err)
}
fmt.Printf("TestNotOmitEmpty: %s\n", jsonData)
testOmitEmptyWithDefaultValue := TestOmitEmptyWithDefaultValue{}
jsonData2, err := json.Marshal(testOmitEmptyWithDefaultValue)
if err != nil {
println(err)
panic(err)
}
fmt.Printf("TestOmitEmptyWithDefaultValue: %s\n", jsonData2)
testOmitEmptyWithDefaultValueButFatherSet := TestOmitEmptyWithDefaultValue{
Uint8: 0,
Uint16: 0,
Uint32: 0,
Uint64: 0,
Int8: 0,
Int16: 0,
Int32: 0,
Int64: 0,
Int: 0,
Float32: 0,
Float64: 0,
Byte: 0,
Rune: 0,
Uintptr: 0,
String: "",
StringPointer: nil,
Array: [10]int{},
Slice: nil,
Map: nil,
Interface: nil,
Error: nil,
}
jsonData3, err := json.Marshal(testOmitEmptyWithDefaultValueButFatherSet)
if err != nil {
println(err)
panic(err)
}
fmt.Printf("testOmitEmptyWithDefaultValueButFatherSet: %s\n", jsonData3)
testOmitEmptyWithNotDefaultValueButFatherSet := TestOmitEmptyWithDefaultValue{
Uint8: 1,
Uint16: 1,
Uint32: 1,
Uint64: 1,
Int8: 1,
Int16: 1,
Int32: 1,
Int64: 1,
Int: 1,
Float32: 1,
Float64: 1,
Byte: 1,
Rune: 1,
Uintptr: 1,
String: "1",
StringPointer: ToStringPointer(""),
Array: [10]int{1},
Slice: []int{1},
Map: map[int]string{1: "1"},
Interface: "1",
Error: errors.New("error"),
}
jsonData4, err := json.Marshal(testOmitEmptyWithNotDefaultValueButFatherSet)
if err != nil {
println(err)
panic(err)
}
fmt.Printf("testOmitEmptyWithNotDefaultValueButFatherSet: %s\n", jsonData4)
}
TestNotOmitEmpty
全部序列化成功。
TestOmitEmptyWithDefaultValue
默认值全军覆没,除了数组。
testOmitEmptyWithDefaultValueButFatherSet
自己设置的默认值也全军覆没,除了数组。
testOmitEmptyWithNotDefaultValueButFatherSet
非默认值当然不会被省略了。
来源:https://juejin.cn/post/7115343247530164254


猜你喜欢
- sql中timestamp和datetime的转换互相转换说明:将datetime转换为timestamp格式,使用UNIX_TIMESTA
- 1. 前言。1.1. 需求背景。 每天抓取的是同一份商品的数据,用来做趋势分析。要求每天都需要抓一份,也仅限抓取一份数据。但是整个
- 背景最近尝试了解Django中ORM实现的原理,发现其用到了metaclass(元类)这一技术,进一步又涉及到Python class中有两
- test.asp 测试演示文件clsrsa.asp 实现rsa加密与解密的vbs类文件下面是代码:1. test.asp<%rem 文
- →问题提出:我用dw做了一个下拉菜单,但是碰到form的列表项就跑到下面去了,请帮忙解决,先谢谢各位了!请看问题图示如下:→解决问题:由于层
- 简要讨论为什么它不提供++作为运算符 正常情况下,当有人问起++原因而不是Python中的运算符时,这一行引起了我的注意。如果您想知道最初的
- 这篇文章主要介绍了python3 反射的四种基本方法解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的
- 选项default-charaset-set=utf8;然后创建一个数据表 create table a_table(b varchar(2
- 如下所示:def list_dict_duplicate_removal(): data_list = [{"a&qu
- 如何用POP3接收电子邮件?POP3大行其道,我看见朋友已经用Jmail和POP3接收邮件了。该如何做?以Jmail4.1为例,我们演示一下
- 上一篇博客主要介绍了决策树的原理,这篇主要介绍他的实现,代码环境python 3.4,实现的是ID3算法,首先为了后面matplotlib的
- 一、通道是什么?其实无论是原子函数还是共享锁都是通过共享内存的方式进行的同步、效率一般不高,而Go语言中则使用了通道,它是一种通过传递信息的
- 最近无意看到网上有人使用Python编写几十行代码生成图像验证码,感觉很是繁琐,这里为各位朋友推荐两种方法,使用4行Python代码即可生成
- Pythond 的函数是由一个新的语句编写,即def,def是可执行的语句--函数并不存在,直到Python运行了def后才存在。函数是通过
- 借助 org.springframework.ui.Model 对象或 Map 对象将信息传到 springmvc 的页面中需要:jstl
- xlwt与xlrd只能针对xls格式的excel进行操作,如果想对xlsx格式进行操作请使用openpyxl模板对excel进行操作xlwt
- 本文介绍在Python环境中,实现随机森林(Random Forest,RF)回归与各自变量重要性分析与排序的过程。其中,关于基于MATLA
- 1. 导入库import numpy as np #矩阵运算import matplotlib.pyplot as plt #可视化impo
- 本文实例为大家分享了python+rsync精确同步指定格式文件的具体代码,供大家参考,具体内容如下# coding: utf-8#!/us
- 概念关键字:array,数据的组合(多个)存储到一个指定的容器中,用变量指向该容器,然后可以通过变量一次性得到该容器中的所有数据.数组定义语