将 null 分配给 JSON 字段而不是空字符串

将 null 分配给 JSON 字段而不是空字符串

问题描述:

由于空字符串是 Go string 的零/默认值,我决定将所有此类字段定义为 interface{}.例如

Since empty string is the zero/default value for Go string, I decided to define all such fields as interface{} instead. for example

type student struct {
    FirstName  interface{} `json:"first_name"`
    MiddleName interface{} `json:"middle_name"`
    LastName   interface{} `json:"last_name"`
}

如果该特定字段的值不可用,我发送数据的应用程序需要一个 null 而不是空字符串.

The application I am sending my data expect a null instead of an empty string if value is not available for that specific field.

这是正确的方法还是有人可以指出比这更好的方法.

Is this the correct approach or can someone please point me to something better than this.

json 包文档 :

指针值编码为指向的值.空指针编码为空 JSON 对象.

Pointer values encode as the value pointed to. A nil pointer encodes as the null JSON object.

所以你可以存储一个指向字符串的指针,如果不是 nil 将被编码为字符串,如果 nil 将被编码为null"

So you can store a pointer to a string which will be encoded as a string if not nil and will be encoded as "null" if nil

type student struct {
  FirstName  *string `json:"first_name"`
  MiddleName *string `json:"middle_name"`
  LastName   *string `json:"last_name"`
}