将 null 分配给 JSON 字段而不是空字符串 [英] Assigning null to JSON fields instead of empty strings

查看:36
本文介绍了将 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"`
}

这篇关于将 null 分配给 JSON 字段而不是空字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆