How to recognize void value and unspecified field when unmarshaling in Go?

后端 未结 1 1687
伪装坚强ぢ
伪装坚强ぢ 2020-12-11 21:44

I would like to know if it\'s possible to differenciate a void value and an unspecified field value.

Here is an example:

var jsonBlob = []byte(`[
           


        
相关标签:
1条回答
  • 2020-12-11 22:01

    You can distinguish between empty and missing values if you change your field type to be a pointer. If the value is present in JSON with an empty string value, it will be set to a pointer that points to an empty string. If it is not present in JSON, it will be left nil.

    type Category struct {
        Name        string
        Description *string
    }
    

    Output (try it on the Go Playground):

    [{Name:A Description:0x1050c150} {Name:B Description:<nil>} {Name:C Description:0x1050c158}]
    
    0 讨论(0)
提交回复
热议问题