dtlrp119999
dtlrp119999
2014-06-24 06:57

golang-如何将字节片转换为bool?

已采纳

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
}
  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

2条回答

  • downloadbooks_2014 downloadbooks_2014 7年前

    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
    }
    
    点赞 评论 复制链接分享
  • drp935159 drp935159 7年前

    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
    }
    
    点赞 评论 复制链接分享

相关推荐