Skip to content

Unable to unmarshal date using json-iterator. #313

Closed
@aafreensheikh96

Description

@aafreensheikh96

I am trying to use a custom struct which implements the json.Unmarshaler interface as a key in a map(map[MyCustomType]bool). This fails when I am trying to use jsoniter but works correctly if I use the standard library json package. Minimal code example to reproduce the issue:

package main

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

    jsoniter "github.com/json-iterator/go"
)

type Date struct {
    time.Time
}

func (d *Date) UnmarshalJSON(b []byte) error {
    dateStr := string(b) // something like `"2017-08-20"`

    if dateStr == "null" {
        return nil
    }

    t, err := time.Parse(`"2006-01-02"`, dateStr)
    if err != nil {
        return fmt.Errorf("cant parse date: %#v", err)
    }

    d.Time = t
    return nil
}

func main() {
    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(fmt.Errorf("standard library unmarshal: %+v", err))
    }

    fmt.Printf("Unmarshalled value using standard library: %+v\n", v)

    if err := jsoniter.Unmarshal(data, &v); err != nil {
        panic(fmt.Errorf("jsoniter unmarshal: %+v", err))
    }

    fmt.Printf("%#v\n", v)
}

Output:

Unmarshalled value using standard library: map[2018-12-14 00:00:00 +0000 UTC:true 2018-12-12 00:00:00 +0000 UTC:true 2018-12-13 00:00:00 +0000 UTC:true]
panic: jsoniter unmarshal: textUnmarshalerDecoder: parsing time "2018-12-12" as "2006-01-02T15:04:05Z07:00": cannot parse "" as "T", error found in #10 byte of ...|018-12-12": true,
  |..., bigger context ...|{
        "2018-12-12": true,
        "2018-12-13": true,
        "2018-|...

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions