Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
sureifyram opened this issue Oct 5, 2021 · 1 comment

Comments

@sureifyram
Copy link

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 \"-\"",
@elliotcourant
Copy link
Collaborator

It looks like you are logging the value of the byte array passed to UnmarshalJSON, what is that log entry say the value is?

Could you also include a stack trace of what code path in go-pg is calling UnmarshalJSON with this bad value?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants