dtlrp119999 2014-06-24 06:57
浏览 1414
已采纳

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 2014-06-24 07:07
    关注

    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
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?