Assigning null to JSON fields instead of empty strings

后端 未结 5 1900
迷失自我
迷失自我 2020-11-29 23:34

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



        
5条回答
  •  孤独总比滥情好
    2020-11-30 00:34

    In json package documentation :

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

    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"`
    }
    

提交回复
热议问题