Golang 语言中 JSON 返回空对象{}

返回默认值

package main

import (
	"encoding/json"
	"fmt"
)

type User struct {
	Uid       int           `json:"uid"`
	UserName  string        `json:"username"`
	LoginInfo UserLoginInfo `json:"logininfo"`
}

type UserLoginInfo struct {
	Time int64 `json:"time"`
}

func main() {
	p := User{Uid: 10, UserName: "weibin"}
	data, _ := json.Marshal(&p)
	fmt.Println(string(data))
}

响应结果:给结构体赋值默认值

{
    "uid":10,
    "username":"weibin",
    "logininfo":{
        "time":0
    }
}

修改指针类型,返回NUll

type User struct {
	Uid       int            `json:"uid"`
	UserName  string         `json:"username"`
	//修改为指针类型
	LoginInfo *UserLoginInfo `json:"logininfo"`  
}

响应结果为Null

{
    "uid":10,
    "username":"weibin",
    "logininfo":null
}

增加 tag:omitempty 不返回该字段

type User struct {
	Uid       int            `json:"uid"`
	UserName  string         `json:"username"`
	//修改为指针类型
	LoginInfo *UserLoginInfo `json:"logininfo,omitempty"`  
}

响应结果:

{
    "uid":10,
    "username":"weibin",
}

调整为 interface{} 返回空对象 {}

package main

import (
	"encoding/json"
	"fmt"
)

type User struct {
	Uid       int         `json:"uid"`
	UserName  string      `json:"username"`
	LoginInfo interface{} `json:"logininfo"`
}

type UserLoginInfo struct {
	Time int64 `json:"time"`
}

func main() {
	p := User{Uid: 10, UserName: "weibin", LoginInfo: struct{}{}}
	data, _ := json.Marshal(&p)
	fmt.Println(string(data))
}

把类型调整为 interface{},并且赋值默认值 struct{}{},会出现预期结果:

{
    "uid":10,
    "username":"weibin",
    "logininfo":{}
}