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

在GORM中如何省略JSON输出里的空嵌入Author结构体?

问题描述

我的项目是REST API,使用GORM作为ORM库。单本书对应一个作者,当未定义作者(无名字和姓氏)时,希望省略整个author字段,但当前JSON输出为"author": {}而非省略该字段。

代码片段

type Author struct {
    FirstName string `json:"first_name,omitempty"`
    LastName  int32  `json:"last_name,omitempty"`
}

type Book struct {
    ID          uint
    Title       string      `gorm:"index;not null" json:"title"`
    Author      Author      `gorm:"embedded" json:"author,omitempty"`
    CreatedAt   time.Time   `json:"created_at"`
    UpdatedAt   time.Time   `json:"updated_at"`
}

解决方案一:将Author改为指针类型

把Book结构体中的Author字段改为指针类型*Author,json:"author,omitempty"标签会在指针为nil时自动省略该字段,同时兼容GORM的嵌入式映射:

type Book struct {
    ID          uint
    Title       string      `gorm:"index;not null" json:"title"`
    // 改为指针类型,nil状态下会被omitempty省略
    Author      *Author     `gorm:"embedded" json:"author,omitempty"`
    CreatedAt   time.Time   `json:"created_at"`
    UpdatedAt   time.Time   `json:"updated_at"`
}

使用注意:

  • 查询数据后,若Author的FirstName和LastName都为空,可手动将Author指针设为nil,确保序列化时省略该字段。
  • 若GORM映射出现问题,可添加前缀标签明确映射关系:gorm:"embedded;embeddedPrefix:author_"

解决方案二:自定义JSON序列化方法

如果不想修改字段类型,可为Book结构体实现MarshalJSON接口,手动控制序列化逻辑:

import "encoding/json"

func (b Book) MarshalJSON() ([]byte, error) {
    // 定义临时结构体,仅保留必要字段并控制Author的显示
    type TempBook struct {
        ID        uint      `json:"id"`
        Title     string    `json:"title"`
        CreatedAt time.Time `json:"created_at"`
        UpdatedAt time.Time `json:"updated_at"`
        Author    *Author   `json:"author,omitempty"`
    }

    temp := TempBook{
        ID:        b.ID,
        Title:     b.Title,
        CreatedAt: b.CreatedAt,
        UpdatedAt: b.UpdatedAt,
    }

    // 仅当Author有有效数据时,才添加到序列化结构中
    if b.Author.FirstName != "" || b.Author.LastName != 0 {
        temp.Author = &b.Author
    }

    return json.Marshal(temp)
}

这种方式无需修改原结构体字段类型,通过临时结构体和自定义判断逻辑,精准控制author字段的显示。


内容的提问来源于stack exchange,提问作者studio-pj

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 03:15:39