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

查看:95
本文介绍了为JSON字段分配null而不是空字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由于空字符串是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包文档中:

指针值编码为指向的值. nil指针编码为空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"`
}

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

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