gpt4 book ai didi

json - Golang JSON 解码到字段,但不编码到 JSON 响应

转载 作者:数据小太阳 更新时间:2023-10-29 03:12:26 29 4
gpt4 key购买 nike

我希望能够访问由 JSON 解码产生的结构字段,但我想在它被编码时使用相同的结构来隐藏该字段。

例子:

type MyStruct struct {
GoodField string `json:"goodField"`
SecretField string `json:"secret"`
}

传入的 JSON 被解码并且 secret 字段可以访问在服务器响应中使用相同的 MyStruct隐藏 secret 字段。

我看过使用 omitempty- 标签,但没有用。

最佳答案

你在 omitempty 上走在了正确的轨道上,你只需将 SecretField 设置为 "" 即可生效

package main

import (
"fmt"
"encoding/json"
)

type MyStruct struct {
GoodField string `json:"goodField"`
SecretField string `json:"secret,omitempty"`
}

func main() {

data := MyStruct{}

s := `{"goodField": "xxx", "secret": "yyy"}`

json.Unmarshal([]byte(s), &data);

fmt.Println(data.GoodField, data.SecretField);

data.SecretField = ""

response, _ := json.Marshal(data)

fmt.Println(string(response))

}

关于json - Golang JSON 解码到字段,但不编码到 JSON 响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47853120/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com