dptiq46022 2017-05-23 22:33
浏览 30
已采纳

我如何在编组时省略结构域(仅*),而在编组时保留它?

I have a User struct with a password field. When I'm creating a user (or udpating with a new password) via POSTed JSON, I want to accept/unmarshal the password field into my object, but whenever I return a user, I want to omit the password field. Below is the best I've been able to come up with so far. It works, but it requires a lot of duplication around the field names that I'd like to eliminate (right now, if I add a new field like FirstName, I have to add that in 3 separate places).

How do I do this better while still honoring the json tags on the struct?

func main() {
    origJson := []byte(`{"id":"1","username":"Chad","pwd":"sillypants"}`)
    fmt.Println("Original:     " + string(origJson))

    var unmarshalled User
    json.Unmarshal(origJson, &unmarshalled)
    fmt.Printf("Unmarshalled: %+v
", unmarshalled)

    marshalled, _ := json.Marshal(unmarshalled)
    fmt.Println("ReMarshalled: " + string(marshalled))
}

type User struct {
    Id       string `json:"id"`
    Username string `json:"username"`
    Password string `json:"pwd"`
}

type SafeUser struct {
    Id       string `json:"id"`
    Username string `json:"username"`
}

func (u User) MarshalJSON() ([]byte, error) {
    safeUser := SafeUser{
        Id      : u.Id,
        Username: u.Username,
    }

    return json.Marshal(safeUser)
}

Try it on the Go Playground

  • 写回答

2条回答 默认 最新

  • dongshan4316 2017-05-24 05:06
    关注

    I had the same issue but came across this article.

    The idea is to use embedding and an anonymous struct to override fields.

    func (u User) MarshalJSON() ([]byte, error) {
        type Alias User
        safeUser := struct {
            Password string `json:"pwd,omitempty"`
            Alias
        }{
            // Leave out the password so that it is empty
            Alias: Alias(u),
        }
    
        return json.Marshal(safeUser)
    }
    

    Try it

    The Alias helps prevent an infinite loop while marshalling.

    Please note that you have to maintain the same JSON field name for the override to work.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)
  • ¥15 keil里为什么main.c定义的函数在it.c调用不了
  • ¥50 切换TabTip键盘的输入法
  • ¥15 可否在不同线程中调用封装数据库操作的类
  • ¥15 微带串馈天线阵列每个阵元宽度计算