版本 go 1.18
前言
在特殊需求需要返回空 json
对象,而不是 null
时,可以参考以下方法
代码
Main
package main
import (
"encoding/json"
"fmt"
)
// ResultResponse 响应体
type ResultResponse struct {
Code int `json:"code"`
Message string `json:"message"`
Data any `json:"data"`
}
func main() {
response := ResultResponse{Code: 0, Message: "success", Data: struct{}{}}
result, _ := json.Marshal(&response)
fmt.Println(string(result))
}
运行结果
{
"code": 0,
"message": "success",
"data": {}
}