error:
panic: textUnmarshalerDecoder: parsing time "2018-10-16" as "2006-01-02T15:04:05Z07:00": cannot parse "" as "T", error found in #10 byte of ...|018-10-16": true,
|..., bigger context ...|{
"2018-10-16": true,
"2018-10-15": true,
"2018-|...
Code:
package main
import (
"errors"
"fmt"
"time"
"github.com/json-iterator/go"
)
const (
DateFmt = `"2006-01-02"`
DateTimeFmt = `"2006-01-02T15:04"`
DateTimeNanoFmt = `"2006-01-02T15:04:05"`
)
var IST, _ = time.LoadLocation("Asia/Kolkata")
var (
dateFormats = []string{DateFmt, DateTimeFmt, DateTimeNanoFmt}
hackDateFormats = map[string]string{`"2006-1-2"`: DateFmt}
)
type Date struct {
time.Time
fmt string
}
func (d *Date) UnmarshalJSON(b []byte) error {
dateStr := string(b) // something like `"2017-08-20"`
if dateStr == "null" {
return nil
}
for _, format := range dateFormats {
if t, err := time.ParseInLocation(format, dateStr, IST); err == nil {
d.Time, d.fmt = t, format
return nil
}
}
for hackFmt, format := range hackDateFormats {
if t, err := time.ParseInLocation(hackFmt, dateStr, IST); err == nil {
d.Time, d.fmt = t, format
return nil
}
}
return errors.New("cant parse date")
}
func main() {
var json = jsoniter.ConfigCompatibleWithStandardLibrary
data := []byte(`{
"2018-12-12": true,
"2018-12-13": true,
"2018-12-14": true
}`)
v := map[Date]bool{}
if err := json.Unmarshal(data, &v); err != nil {
panic(err)
}
fmt.Printf("%#v\n", v)
}
but this same works when I use "encoding/json" library
error: panic: textUnmarshalerDecoder: parsing time "2018-10-16" as "2006-01-02T15:04:05Z07:00": cannot parse "" as "T", error found in #10 byte of ...|018-10-16": true, |..., bigger context ...|{ "2018-10-16": true, "2018-10-15": true, "2018-|...
Code:
but this same works when I use "encoding/json" library
output: map[jsonutil.Date]bool{jsonutil.Date{Time:time.Time{wall:0x0, ext:63680149800, loc:(time.Location)(0xc420134120)}, fmt:"\"2006-01-02\""}:true, jsonutil.Date{Time:time.Time{wall:0x0, ext:63680236200, loc:(time.Location)(0xc420134120)}, fmt:"\"2006-01-02\""}:true, jsonutil.Date{Time:time.Time{wall:0x0, ext:63680322600, loc:(*time.Location)(0xc420134120)}, fmt:"\"2006-01-02\""}:true}
code: