json - 如何在输入时跳过 Struct 中的 JSON 字段并在输出中显示它们,以及在输入中接受某些字段并在 Golang 中在输出中跳过它们?

标签 json go struct go-gorm

我正在使用 Echo 框架和 Gorm 在 Go 中编写网络服务。 我有一个如下所示的 User 结构:

type User struct {
    ID    uint   `json:"user_id"`
    Email string `json:"email_address,omitempty" validate:"required,email"`
}

我正在接受带有 Content-type: application/jsonPOST 请求。 我希望我的输入是 {"email_address": "email@email.com"} 并且我的输出是 {"user_id": 1}

如何禁止用户在请求中提交ID(这样他们就不能创建具有特定ID的记录),但保留ID在响应中? 现在我正在保存之前执行 user.ID = 0,但我想知道是否有更好的方法来做到这一点?

我还想在输出中跳过 Email。现在我正在输出之前执行 user.Email = "" 。还有更好的方法吗?

谢谢!

最佳答案

虽然 icza 的回答提出了一个很好的解决方案,但您也可以使用 JSON 编码辅助方法 MarshalJSON/UnmarshalJSON:

func main() {
    // employing auxiliary json methods MarshalJSON/UnmarshalJSON
    user := User{ID: 123, Email: `abc@xyz.com`}
    js, _ := json.Marshal(&user)
    log.Printf("%s", js)

    input := UserInput(user)
    js, _ = json.Marshal(&input)
    log.Printf("%s", js)

    output := UserOutput(user)
    js, _ = json.Marshal(&output)
    log.Printf("%s", js)
}

type User struct {
    ID    uint   `json:"user_id"`
    Email string `json:"email_address,omitempty" validate:"required,email"`
}

type UserInput User

func (x *UserInput) MarshalJSON() ([]byte, error) {
    return json.Marshal(&struct {
        Email string `json:"email_address,omitempty" validate:"required,email"`
    }{
        Email: x.Email,
    })
}

type UserOutput User

func (x *UserOutput) MarshalJSON() ([]byte, error) {
    return json.Marshal(&struct {
        ID uint `json:"user_id"`
    }{
        ID: x.ID,
    })
}

这给了我们:

[  info ] main.go:25: {"user_id":123,"email_address":"abc@xyz.com"}
[  info ] main.go:29: {"email_address":"abc@xyz.com"}
[  info ] main.go:33: {"user_id":123}

关于 Go Playground .

关于json - 如何在输入时跳过 Struct 中的 JSON 字段并在输出中显示它们,以及在输入中接受某些字段并在 Golang 中在输出中跳过它们?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42086071/

相关文章:

ruby-on-rails - 渲染 :json does not accept options

c - 使用结构和动态内存分配的队列

struct - Common Lisp 按顺序处理结构槽

asp.net-mvc - 如何将 XML 作为 POST 传递给 ASP MVC .NET 中的 ActionResult

java - Retrofit Jackson 转换器无法识别嵌套对象

javascript - 如何访问每个键具有多个值的 JSON 对象?

go - 为什么不byte.NewBuffer接受全身请求?

go - 去http.FileServer流错误的文件

function - 通过在 Go 中不允许嵌套函数声明可以缓解哪些问题?

C11 - 执行两次重新分配时,结构数组上的重新分配失败