英文:
GORM omit fields in a JSON Response
问题
我想要在我的JSON响应中省略一些字段。
目前我有一个类型为receiver
的函数,返回一个新的结构体userToJson
。
然后我将其传递给json.NewEncoder()
。但是我想知道是否有更好的方法来使用GORM省略字段。
谢谢!
英文:
I would like to omit some fields in my JSON Response.
Currently I have a type receiver that returns a new struct userToJson
.
I then pass this to the json.NewEncoder()
. However I am wondering if this is the best way to omit fields using 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,
}
}
答案1
得分: 2
另一种方法是为您的类型实现Marshaler
接口,以修改JSON序列化的方式。在进行序列化之前,json
包会检查该接口是否存在,并调用相应的函数。以下是标准库中的接口定义。
type Marshaler interface {
MarshalJSON() ([]byte, error)
}
下面是针对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)
}
英文:
Another approach is to implement the interface Marshaler
for your type to modify how marshaling to JSON works. The json
package checks for that interface before marshaling, and if it exists, calls that function. 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.
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)
}
答案2
得分: 0
你应该为所有字段在结构体中声明一个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"`
}
英文:
you should declare you struct with a json tag for all fields, what Behrooz suggested in the comment should work fine
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"`
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论