简体   繁体   中英

GORM omit fields in a JSON Response

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,
    }
}

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)
}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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