Skip to content

Custom time.Time type is not receiving the complete date in UnmarshalJSON method. #1928

Open
@sureifyram

Description

@sureifyram

Custom time.Time type is not receiving the complete date in UnmarshalJSON method.

Example Struct using the custom type JsonDate

type BeneficiaryTrust struct {
	tableName       struct{} `pg:"beneficiaries_trust"`
	ID              int64
	CreatedAt       time.Time   `json:"createdAt"`
	UpdatedAt       time.Time   `json:"updatedAt"`
	Name            string      `json:"name"`
	Established     db.JsonDate `json:"established"`
}
type JsonDate time.Time

func (j *JsonDate) UnmarshalJSON(b []byte) error {
	logger.GetLogger().Infof("%v",string(b))
	s := strings.Trim(string(b), "\"")
	t, err := time.Parse("2006-01-02", s)
	if err!=nil {
		return err
	}
	*j = JsonDate(t)
	return nil
}

func (j JsonDate) MarshalJSON() ([]byte, error) {
	return json.Marshal(time.Time(j))
}

Following go-pg method is failing with below error

var tBenes []models.BeneficiaryTrust
_, err = DB.Query(&tBenes, "select * from table")

ERROR:

parsing time \"2021\" as \"2006-01-02\": cannot parse \"\" as \"-\"",

Expected Behavior

All the database records from the table need to unmarshall properly into tBenes struct variable.

Current Behavior

Receiving the below error

parsing time \"2021\" as \"2006-01-02\": cannot parse \"\" as \"-\"",

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