首頁 > 後端開發 > Golang > 主體

在 Go 中解組 sql.NullTime 結構

PHPz
發布: 2024-02-09 14:42:09
轉載
1158 人瀏覽過

在 Go 中解组 sql.NullTime 结构

php小編小新在Go語言中,我們常常會使用sql.NullTime結構來處理資料庫中的時間欄位。 NullTime結構可以表示一個可空的時間值,非常適合處理資料庫中的空值。在本文中,我們將介紹如何解組sql.NullTime結構,以及如何正確處理其中可能存在的空值情況。無論您是初學者還是有一定經驗的開發者,本文都將為您提供清晰的指導,幫助您更好地理解並使用NullTime結構。

問題內容

給定

type NullTime struct {
    Time  time.Time
    Valid bool // Valid is true if Time is not NULL
}
登入後複製

type PayinCount struct {
    DateShiftStart sql.NullTime    `json:"dateShiftStart"`
    DateShiftEnd   sql.NullTime    `json:"dateShiftend"`
}
登入後複製

當我處理以下 JSON 時

{
    "dateShiftStart":"2023-10-16",
    "dateShiftEnd":"2023-10-23"
}
登入後複製
登入後複製

var payinsCount PayinsCount
err = json.Unmarshal(body, &payinsCount)
if err != nil {
    sendErrorResponse(w, err.Error(), http.StatusBadRequest)
    return
}
登入後複製
登入後複製

其中 sendErrorResponse 是以下輔助程序

func sendErrorResponse(w http.ResponseWriter, err string, statusCode int) {
    messageStatusCode := MessageStatusCode{
        Message:    err,
        StatusCode: statusCode}
    w.WriteHeader(statusCode)
    json.NewEncoder(w).Encode(messageStatusCode)
}
登入後複製

我收到以下訊息

{
    "message": "json: cannot unmarshal string into Go struct field PayinsCount.dateShiftStart of type sql.NullTime",
    "statusCode": 400
}
登入後複製

如何解決這個問題?

解決方法

我最終使用了以下內容。 我添加了以下類型。

type NullDate sql.NullTime
登入後複製

然後我將 PayinsCount 更改為使用 NullDate

type PayinsCount struct {
    DateShiftStart NullDate      `json:"dateShiftStart,omitempty"`
    DateShiftEnd   NullDate      `json:"dateShiftend,omitempty"`
}
登入後複製

然後我創建了

// UnmarshalJSON for NullDate
func (nd *NullDate) UnmarshalJSON(b []byte) error {
    s := string(b)
    s = strings.ReplaceAll(s, "\"", "")

    x, err := time.Parse(time.DateOnly, s)
    if err != nil {
        nd.Valid = false
        return err
    }

    nd.Time = x
    nd.Valid = true
    return nil
}
登入後複製

現在當我處理以下 JSON 時

{
    "dateShiftStart":"2023-10-16",
    "dateShiftEnd":"2023-10-23"
}
登入後複製
登入後複製

var payinsCount PayinsCount
err = json.Unmarshal(body, &payinsCount)
if err != nil {
    sendErrorResponse(w, err.Error(), http.StatusBadRequest)
    return
}
登入後複製
登入後複製

它有效。我最終得到了一個有效的 PayinsCount 實例。

為了完整起見,這裡是 NullDate 的 MarshalJSON 函數

// MarshalJSON for NullDate
func (nd NullDate) MarshalJSON() ([]byte, error) {
    if !nd.Valid {
        return []byte("null"), nil
    }
    val := fmt.Sprintf("\"%s\"", nd.Time.Format(time.DateOnly))
    return []byte(val), nil
}
登入後複製

注意轉義的雙引號 - 如果沒有它們,encoding/json 編組程式碼將以 3 個區塊的形式處理日期字串,並且我收到以下錯誤

error(*encoding/json.SyntaxError) *{msg: "invalid character '-' after top-level value", Offset: 0}
登入後複製

以上是在 Go 中解組 sql.NullTime 結構的詳細內容。更多資訊請關注PHP中文網其他相關文章!

相關標籤:
來源:stackoverflow.com
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
最新問題
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!