Golang中encoding/json关于omitempty的坑
json
适用于现代 C++ 的 JSON。
项目地址:https://gitcode.com/gh_mirrors/js/json

·
一句话概括
omitempty标签并不是省略空值, 而是省略变量类型对应的零值. 如果刚好赋值为零值, 会被json.Marshal方法省略掉. (我认为是bug)
发现问题
type TestStruct struct {
BoolVar bool `json:"bool_var,omitempty"`
IntVar int `json:"int_var,omitempty"`
StringVar string `json:"string_var,omitempty"`
InterfaceVar interface{} `json:"interface,omitempty"`
}
这样的一个结构, 带上omitempty的tag, 本来是希望几个值不赋值时就不序列化. 但发现赋值后也会被省略.
例如业务场景中, 一个布尔类型的值带上了omitempt, 那么只会返回true, false时就没有这个字段, 显然不是我们想要的.
InterfaceVarIsInt := TestStruct{
BoolVar: false,
IntVar: 0,
InterfaceVar: 0,
StringVar: "",
}
res, _ := json.Marshal(InterfaceVarIsInt)
fmt.Println(string(res))
输出:
{"interface":0}
原因与解决
false/0/""刚好都是bool类型, int类型和string类型的零值, json不会判断有没有主动赋值, 都会被省略.
如果想要实现, 不赋值的变量就不会序列化返回, 应该使用interface{}, 因为interface{}的零值是nil, 只要有手动赋值,就不会是nil.
完整代码
package main
import (
"fmt"
"encoding/json"
)
type TestStruct struct {
BoolVar bool `json:"bool_var,omitempty"`
IntVar int `json:"int_var,omitempty"`
StringVar string `json:"string_var,omitempty"`
InterfaceVar interface{} `json:"interface,omitempty"`
}
func main() {
InterfaceVarIsInt := TestStruct{
BoolVar: false,
IntVar: 0,
InterfaceVar: 0,
StringVar: "",
}
res, _ := json.Marshal(InterfaceVarIsInt)
fmt.Println(string(res))
InterfaceVarIsBool := TestStruct{
BoolVar: false,
IntVar: 0,
InterfaceVar: false,
StringVar: "",
}
res, _ = json.Marshal(InterfaceVarIsBool)
fmt.Println(string(res))
}
输出,不会省略零值:
{"interface":0}
{"interface":false}




适用于现代 C++ 的 JSON。
最近提交(Master分支:17 天前 )
230bfd15
Bumps [actions/dependency-review-action](https://github.com/actions/dependency-review-action) from 4.6.0 to 4.7.0.
- [Release notes](https://github.com/actions/dependency-review-action/releases)
- [Commits](https://github.com/actions/dependency-review-action/compare/ce3cf9537a52e8119d91fd484ab5b8a807627bf8...38ecb5b593bf0eb19e335c03f97670f792489a8b)
---
updated-dependencies:
- dependency-name: actions/dependency-review-action
dependency-version: 4.7.0
dependency-type: direct:production
update-type: version-update:semver-minor
...
Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> 5 天前
e9391dc5
Bumps [lukka/get-cmake](https://github.com/lukka/get-cmake) from 4.0.1 to 4.02.
- [Release notes](https://github.com/lukka/get-cmake/releases)
- [Commits](https://github.com/lukka/get-cmake/compare/57c20a23a6cac5b90f31864439996e5b206df9dc...ea004816823209b8d1211e47b216185caee12cc5)
---
updated-dependencies:
- dependency-name: lukka/get-cmake
dependency-version: '4.02'
dependency-type: direct:production
...
Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> 7 天前
更多推荐
所有评论(0)