golang – How to convert byte slice to bool?

huangapple go评论68阅读模式
英文:

golang - How to convert byte slice to bool?

问题

我有一个数据库的 sql.NullBool 类型。为了将 JSON 反序列化到它,我正在编写这个小函数。我可以通过简单地将字节数组转换为字符串来将其转换为字符串(string(data)),但对于布尔值来说不是这样。你有什么办法可以将其转换为布尔值吗?

type NullBool struct {
    sql.NullBool
}

func (b *NullBool) UnmarshalJSON(data []byte) error {
  b.Bool = bool(data) //BREAKS!! 
  b.Valid = true
  return nil
}
英文:

I have a database sql.NullBool. To unmarshal json into it, I am writing this little function. I can converty the byte array to string by simply casting it (string(data))...not so for bool. Any idea how I can convert to bool?

type NullBool struct {
    sql.NullBool
}

func (b *NullBool) UnmarshalJSON(data []byte) error {
  b.Bool = bool(data) //BREAKS!! 
  b.Valid = true
  return nil
}

答案1

得分: 9

最简单的方法是使用strconv.ParseBool包。像这样:

func (b *NullBool) UnmarshalJSON(data []byte) error {
    var err error
    b.Bool, err = strconv.ParseBool(string(data))
    b.Valid = (err == nil)
    return err
}

这段代码的作用是将JSON数据解析为NullBool类型。它使用strconv.ParseBool函数将JSON字符串转换为布尔值,并将结果存储在b.Bool中。如果转换成功,b.Valid将被设置为true,否则为false。最后,函数返回可能出现的错误。

英文:

The simplest way would be to use the strconv.ParseBool package. Like this:

func (b *NullBool) UnmarshalJSON(data []byte) error {
    var err error
    b.Bool, err = strconv.ParseBool(string(data))
    b.Valid = (err == nil)
    return err
}

答案2

得分: 4

你可以几乎直接使用json模块。

func (nb *NullBool) UnmarshalJSON(data []byte) error {
    err := json.Unmarshal(data, &nb.Bool)
    nb.Valid = (err == nil)
    return err
}
英文:

You can use the json module almost directly.

func (nb *NullBool) UnmarshalJSON(data []byte) error {
    err := json.Unmarshal(data, &nb.Bool)
    nb.Valid = (err == nil)
    return err
}

答案3

得分: 0

我认为简单的方法是检查切片的长度,可以这样做:

b := []byte("data")
isByteSliceValid := len(b) != 0
英文:

It think the simple way is to check the slice length like so:

b := []byte("data")
isByteSliceValid := len(b) != 0

huangapple
  • 本文由 发表于 2014年6月24日 14:57:31
  • 转载请务必保留本文链接:https://go.coder-hub.com/24380229.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定