How to recognize void value and unspecified field

2019-01-20 12:09发布

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(`[
    {"Name": "A", "Description": "Monotremata"},
    {"Name": "B"},
    {"Name": "C", "Description": ""}
]`)

type Category struct {
    Name  string
    Description string
}

var categories []Category
err := json.Unmarshal(jsonBlob, &categories)

if err != nil {
    fmt.Println("error:", err)
}
fmt.Printf("%+v", categories)

Also available here: https://play.golang.org/p/NKObQB5j4O

Output:

[{Name:A Description:Monotremata} {Name:B Description:} {Name:C Description:}]

So in this example is it possible to differentiate the description from the category B from the category C?

I just want to be able to differentiate them to have different behavior in the program.

1条回答
成全新的幸福
2楼-- · 2019-01-20 12:56

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}]
查看更多
登录 后发表回答