You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Golang:返回类型为string时如何返回null值

解决Go结构体JSON序列化时空字符串转null的问题

针对你遇到的EventDate为空时JSON返回null而非空字符串的需求,有两种常用的实现方式:

方法一:使用字符串指针类型

将结构体中的EventDate字段类型从string改为*string。Go语言中指针的零值是nil,json.Marshal会将nil序列化为JSON的null。

修改后的结构体:

type Country struct {
    WhoAllAreComing []string `json:"attendees"`
    NameOfThePlace  string   `json:"name"`
    EventDate       *string  `json:"eventDate"`
}

赋值示例:

// 当有日期值时
dateStr := "2024-10-01"
country := Country{
    NameOfThePlace: "Beijing",
    EventDate:      &dateStr, // 取字符串地址赋值
}

// 当日期为空时,直接保持EventDate为nil(零值)
emptyCountry := Country{
    NameOfThePlace: "Shanghai",
    // 不赋值EventDate,默认就是nil
}

序列化后,emptyCountry的JSON结果中eventDate会是null。

方法二:自定义JSON序列化逻辑

如果不想修改字段类型,可以给结构体实现json.Marshaler接口,手动控制序列化行为。

示例代码:

import "encoding/json"

type Country struct {
    WhoAllAreComing []string `json:"attendees"`
    NameOfThePlace  string   `json:"name"`
    EventDate       string   `json:"eventDate"`
}

// 实现json.Marshaler接口
func (c Country) MarshalJSON() ([]byte, error) {
    // 定义临时结构体继承原结构体重写EventDate字段
    type TempCountry Country
    temp := struct {
        TempCountry
        EventDate *string `json:"eventDate"`
    }{
        TempCountry: TempCountry(c),
    }

    // 原字段不为空时赋值指针,为空则保持nil
    if c.EventDate != "" {
        temp.EventDate = &c.EventDate
    }

    return json.Marshal(temp)
}

这样,当EventDate为空字符串时,序列化后的JSON中该字段会是null;不为空时则正常显示字符串值。


内容的提问来源于stack exchange,提问作者lily

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.21 20:54:27