简体   繁体   English

GORM 在 JSON 响应中省略字段

[英]GORM omit fields in a JSON Response

I would like to omit some fields in my JSON Response.我想在我的 JSON 响应中省略一些字段。 Currently I have a type receiver that returns a new struct userToJson .目前我有一个类型接收器,它返回一个新的 struct userToJson I then pass this to the json.NewEncoder() .然后我将它传递给json.NewEncoder() However I am wondering if this is the best way to omit fields using GORM.但是我想知道这是否是使用 GORM 省略字段的最佳方法。

Thank you beforehand!预先感谢您!

package server

import (
    "gorm.io/gorm"
)

type User struct {
    gorm.Model
    FirstName string `gorm:"not null;default:null"`
    LastName  string `gorm:"not null;default:null"`
    Email     string `gorm:"not null;default:null;unique"`
    Password  string `gorm:"not null;default:null"`
    Posts     []Posts
}
type userToJson struct {
    Email string
    Posts []Posts
}

func (u *User) toJson() userToJson {
    return userToJson{
        Email: u.Email,
        Posts: u.Posts,
    }
}

Another approach is to implement the interface Marshaler for your type to modify how marshaling to JSON works.另一种方法是为您的类型实现接口Marshaler以修改编组到 JSON 的工作方式。 The json package checks for that interface before marshaling, and if it exists, calls that function. json包在编组之前检查该接口,如果存在,则调用该函数。 Here is the interface from the standard library.这是标准库的接口。

type Marshaler interface {
    MarshalJSON() ([]byte, error)
}

One sample implementation for your User type would be as follows.您的User类型的一个示例实现如下。

func (u *User) MarshalJSON() ([]byte, error) {
    type Temp struct {
        Email string
        Posts []Post
    }

    t := Temp{
        Email: u.Email,
        Posts: u.Posts,
    }
    return json.Marshal(&t)
}

you should declare you struct with a json tag for all fields, what Behrooz suggested in the comment should work fine您应该为所有字段声明一个带有 json 标记的结构,Behrooz 在评论中建议的内容应该可以正常工作

type User struct {
    gorm.Model
    FirstName string `json:"-" gorm:"not null;default:null"`
    LastName  string `json:"-" gorm:"not null;default:null"`
    Email     string `json:"email" gorm:"not null;default:null;unique"`
    Password  string `json:"-" gorm:"not null;default:null"`
    Posts     []Posts`json:"posts"`
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM