在Go中解组时,如何识别空值和未指定的字段? [英] How to recognize void value and unspecified field when unmarshaling in Go?

查看:197
本文介绍了在Go中解组时,如何识别空值和未指定的字段?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否可以区分一个空值和一个未指定的字段值。

下面是一个例子:

  var jsonBlob = [] byte(`[
{Name:A,Description:Monotremata}} ,
{Name:B},
{Name:C,Description:}
]`)

类型类别struct {
名称字符串
描述字符串
}

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

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

也可在此处找到: https://play.golang.org/p/NKObQB5j4O



输出:


$ $ p $ [{名称:A说明:Monotremata} {名称:B说明:} {名称:C说明:}]

所以在这个例子中可以diff从类别C中描述类别B的描述?



我只是希望能够区分它们在程序中具有不同的行为。 $ b

解决方案

如果您将字段类型更改为指针,则可以区分空值和缺失值。如果值在JSON中以空字符串值存在,则它将设置为指向空字符串的指针。如果它没有出现在JSON中,它将被留下 nil

 类型类别struct {
名称字符串
描述*字符串
}

输出(在去游乐场试试):

  [{名称:A描述:0x1050c150} {名称:B描述:< nil>} {名称:C描述:0x1050c158}] 


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.

解决方案

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}]

这篇关于在Go中解组时,如何识别空值和未指定的字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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