在Go中解组sql.NullTime结构

jdg4fx2g  于 2023-11-14  发布在  Go
关注(0)|答案(1)|浏览(111)

给定

  1. type NullTime struct {
  2. Time time.Time
  3. Valid bool // Valid is true if Time is not NULL
  4. }

字符串

  1. type PayinCount struct {
  2. DateShiftStart sql.NullTime `json:"dateShiftStart"`
  3. DateShiftEnd sql.NullTime `json:"dateShiftend"`
  4. }


当我处理下面的JSON时,

  1. {
  2. "dateShiftStart":"2023-10-16",
  3. "dateShiftEnd":"2023-10-23"
  4. }


  1. var payinsCount PayinsCount
  2. err = json.Unmarshal(body, &payinsCount)
  3. if err != nil {
  4. sendErrorResponse(w, err.Error(), http.StatusBadRequest)
  5. return
  6. }


其中sendErrorResponse是以下帮助进程

  1. func sendErrorResponse(w http.ResponseWriter, err string, statusCode int) {
  2. messageStatusCode := MessageStatusCode{
  3. Message: err,
  4. StatusCode: statusCode}
  5. w.WriteHeader(statusCode)
  6. json.NewEncoder(w).Encode(messageStatusCode)
  7. }


我收到以下信息

  1. {
  2. "message": "json: cannot unmarshal string into Go struct field PayinsCount.dateShiftStart of type sql.NullTime",
  3. "statusCode": 400
  4. }


如何解决此问题?

jhdbpxl9

jhdbpxl91#

最后我使用了下面的代码。我添加了下面的类型。

  1. type NullDate sql.NullTime

字符串
然后我将PayinsCount更改为使用NullDate

  1. type PayinsCount struct {
  2. DateShiftStart NullDate `json:"dateShiftStart,omitempty"`
  3. DateShiftEnd NullDate `json:"dateShiftend,omitempty"`
  4. }


然后我创造了

  1. // UnmarshalJSON for NullDate
  2. func (nd *NullDate) UnmarshalJSON(b []byte) error {
  3. s := string(b)
  4. s = strings.ReplaceAll(s, "\"", "")
  5. x, err := time.Parse(time.DateOnly, s)
  6. if err != nil {
  7. nd.Valid = false
  8. return err
  9. }
  10. nd.Time = x
  11. nd.Valid = true
  12. return nil
  13. }


当我处理下面的JSON时,

  1. {
  2. "dateShiftStart":"2023-10-16",
  3. "dateShiftEnd":"2023-10-23"
  4. }


  1. var payinsCount PayinsCount
  2. err = json.Unmarshal(body, &payinsCount)
  3. if err != nil {
  4. sendErrorResponse(w, err.Error(), http.StatusBadRequest)
  5. return
  6. }


它工作了。我最终得到了一个有效的PayinsCount示例。
为了完整起见,这里是NullDate的MarshalJSON函数

  1. // MarshalJSON for NullDate
  2. func (nd NullDate) MarshalJSON() ([]byte, error) {
  3. if !nd.Valid {
  4. return []byte("null"), nil
  5. }
  6. val := fmt.Sprintf("\"%s\"", nd.Time.Format(time.DateOnly))
  7. return []byte(val), nil
  8. }


注意转义的双引号--如果没有它们,encoding/json编组代码将在3个块中处理日期字符串,我得到以下错误

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

展开查看全部

相关问题