How to Marshal / Unmarshal Json with a Custom Type Attribute in Go

Created
Modified

JSON (JavaScript Object Notation) is a lightweight data-interchange format.

Using UnmarshalJSON Function

Example on custom UnmarshalJSON and MarshalJSON.

The following example should cover whatever you are trying to do:

package main

import (
  "encoding/json"
  "fmt"
  "strconv"
  "time"
)

type CustTimeUinx int64

func (t *CustTimeUinx) UnmarshalJSON(b []byte) error {

  s, _ := strconv.Unquote(string(b))

  uinx := int64(0)
  if len(s) != 0 {
    d, _ := time.Parse("2006-01-02 15:04:05", s)
    uinx = d.Unix()
  }

  *t = CustTimeUinx(uinx)
  return nil
}

func (t *CustTimeUinx) MarshalJSON() ([]byte, error) {
  uinx := int64(*t)
  quoted := strconv.Quote(time.Unix(uinx, 0).Format("2006-01-02 15:04:05"))
  return []byte(quoted), nil

}

type TestItem struct {
  Curr CustTimeUinx `json:"Curr"`
}

func main() {

  // Unmarshal Json
  s := `{"curr":"2022-06-26 10:00:00", "age":10}`
  var data TestItem
  json.Unmarshal([]byte(s), &data)

  b, _ := json.MarshalIndent(data, "", "  ")
  fmt.Printf("%s\n", b)

  // Marshal Json
  d := TestItem{
    Curr: CustTimeUinx(1656237600),
  }

  js, _ := json.Marshal(&d)
  fmt.Printf("%s\n", js)
}
{
  "Curr": 1656237600
}
{"Curr":"2022-06-26 18:00:00"}

Related Tags