GORM在JSON响应中省略字段。

huangapple go评论67阅读模式
英文:

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"`
}

huangapple
  • 本文由 发表于 2022年7月14日 02:59:33
  • 转载请务必保留本文链接:https://go.coder-hub.com/72971337.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定