Go and JSON

來源:互聯網
上載者:User

標籤:

Go and JSON

在使用Go開發web項目的過程中, 資料庫讀寫操作與JSON格式的輸入輸出是兩塊最基礎的模組, Go的標準庫已經幫我們做了很多, 熟悉database/sql與encoding/json這兩個庫能幫我們更自在地開發web應用.

但此篇文章拋開基礎不說, 只說一些在開發中遇到一些真實存在的痛點.

如何處理Null值?

Go的一大特色就是zero value, 比如int類型的zero value是0, string為"", struct為每個field裡各自類型的zero value. 因此在Go的很多ORM處理NULL值時, 都是通過zero value機制入庫或出庫的, 因此, 使用ORM操作的資料庫, 如何沒有明確指明, 基本上看不到NULL值. 一個可能為NULL的varchar欄位, 存入了""(Null 字元串).

這裡不討論關於Null 字元串與NULL的優劣, 而是說明如何處理NULL值.

sql標準庫裡帶了這麼幾個類型: ```sql.NullString, sql.NullInt64, sql.NullBool, sql.NullFloat64```, 如果在定義struct裡field類型的時候, 使用sql.NullString代替string的話, 就可以在資料庫裡存入NULL值.

通過源碼看到, NullString的結構與兩個方法:

type NullString struct{    String string    Valid bool}Scan(value interface{}) errorValue()(driver.Value, error)

Scan實現了sql.Scanner介面, Value實現了driver.Valuer介面. 這兩個介面表示資料從Go端與DB端的轉換. Scan用於資料從DB轉到Go時被調用,也就是說select時用(查看源碼); 而Value則由Go轉到DB時被調用. 也就是說insert/update時候用(查看源碼).

在兩個不同領域做資料轉換時, 通常用介面來定義, 這是介面的作用, JSON也是同樣如此.

有了介面的協助, 任何實現了這兩個介面的類型, 都能在DB與Go之間做轉換, 介面建立起了橋樑.

如何處理自訂類型?

由上一節可以想到, 如果在想要儲存Go自訂類型到DB裡, 只需要實現Scanner與Valuer介面, 就像sql.NullString一樣.

典型如NullTime(查看源碼):

type NullTime struct {    Time  time.Time    Valid bool}func (nt *NullTime) Scan(value interface{}) error {    nt.Time, nt.Valid = value.(time.Time)    return nil}func (nt NullTime) Value() (driver.Value, error) {    if !nt.Valid {        return nil, nil    }    return nt.Time, nil}

為了讓這個類型更好用, 添加一個協助函數:

func ToNullTime(t time.Time) NullTime {    return NullTime{Time: t, Valid: !t.IsZero()}}

自訂類型如何轉化成JSON?

如果拿一個sql.NullString的類型, 做json.Marshal, 那麼得到輸出是這樣的:

{    ...    "column_name" : { "String" : "Hello?", "Valid" : true },    ...}//而我們想要的是:{    ...    "column_name" : "Hello?",    ...}//or{    ...    "column_name" : null,    ...}

我們知道, json庫有兩個標準的介面, json.Marshaler(查看源碼) , json.Unmarshaler(查看源碼), 如果一個類型實現此兩個介面, 則在使用json.Marshal/Unmarshal調用時, 調用此類型的自訂方法:

type NullString struct {    sql.NullString}func(v *NullString) MarshalJSON() ([]byte, error) {    if v.Valid {        return json.Marshal(v.String)    } else {        return json.Marshal(nil)    }}func (v NullString) UnmarshalJSON(data []byte) error {    var s *string    if err := json.Unmarshal(data, &s); err != nil {        return err    }    if s != nil {        v.Valid = true        v.String = *s    } else {        v.Valid = false    }    return nil}

 

總結

Go語言的介面, 扮演了橋樑的角色, 串連起了Go與其它領域的資料轉換, 通過實現標準庫的介面, 我們可以讓Go的資料類型輕鬆適應不同資料領域.


[參考]
http://dennissuratna.com/marshalling-nullable-string-db-value-to-json-in-go/

http://blog.carbonfive.com/2015/07/09/there-will-be-sql/

http://marcesher.com/2014/10/13/go-working-effectively-with-database-nulls/

Go and JSON

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.