toString, _ := jsoniter.MarshalToString(people)
t.Logf("%s", toString) // {"name":"testName"}
1.无法忽略掉嵌套结构体,可以通过定义为指针类型来解决
package test
import (
jsoniter "github.com/json-iterator/go"
"testing"
type People struct {
Name string `json:"name"`
Age int `json:"age,omitempty"`
Info Info `json:"info,omitempty"`
type Info struct {
Height int `json:"height"`
Weight int `json:"weight"`
func TestJson(t *testing.T) {
people := People{}
str := `{
"name": "testName",
"age": 0
err := jsoniter.UnmarshalFromString(str, &people)
if err != nil {
return
toString, _ := jsoniter.MarshalToString(people)
t.Logf("%s", toString) // {"name":"testName","info":{"height":0,"weight":0}}
------------------------------
// 重新定义结构体
type People struct {
Name string `json:"name"`
Age int `json:"age,omitempty"`
Info *Info `json:"info,omitempty"`
type Info struct {
Height int `json:"height"`
Weight int `json:"weight"`
// {"name":"testName"}
2.如果字段标签有omitempty,恰巧默认值是有意义的,这个时候也会忽略掉,解决办法也是通过定义为指针类型来解决
package test
import (
jsoniter "github.com/json-iterator/go"
"testing"
type People struct {
Name string `json:"name"`
Age *int `json:"age,omitempty"` // 定义为指针类型
func TestJson(t *testing.T) {
people := People{}
str := `{
"name": "testName",
"age": 0
err := jsoniter.UnmarshalFromString(str, &people)
if err != nil {
return
toString, _ := jsoniter.MarshalToString(people)
t.Logf("%s", toString) // {"name":"testName","age":0}
// 结构体初始化
func TestJson1(t *testing.T) {
age := 0
people := People{
Name: "testName",
Age: &age,
toString, _ := jsoniter.MarshalToString(people)
t.Logf("%s", toString) // {"name":"testName","age":0}