From 63f58fd32edb5684b9e9f4cfaac847c6b42b3917 Mon Sep 17 00:00:00 2001 From: Jack Christensen Date: Fri, 29 Sep 2017 15:25:53 -0500 Subject: [PATCH] Add UnmarshalJSON to a few types --- pgtype/int4.go | 13 +++++++++++++ pgtype/text.go | 12 ++++++++++++ pgtype/varchar.go | 4 ++++ 3 files changed, 29 insertions(+) diff --git a/pgtype/int4.go b/pgtype/int4.go index 37d00511..261c5118 100644 --- a/pgtype/int4.go +++ b/pgtype/int4.go @@ -3,6 +3,7 @@ package pgtype import ( "database/sql/driver" "encoding/binary" + "encoding/json" "math" "strconv" @@ -198,3 +199,15 @@ func (src *Int4) MarshalJSON() ([]byte, error) { return nil, errBadStatus } + +func (dst *Int4) UnmarshalJSON(b []byte) error { + var n int32 + err := json.Unmarshal(b, &n) + if err != nil { + return err + } + + *dst = Int4{Int: n, Status: Present} + + return nil +} diff --git a/pgtype/text.go b/pgtype/text.go index e7fba682..bceeffd4 100644 --- a/pgtype/text.go +++ b/pgtype/text.go @@ -149,3 +149,15 @@ func (src *Text) MarshalJSON() ([]byte, error) { return nil, errBadStatus } + +func (dst *Text) UnmarshalJSON(b []byte) error { + var s string + err := json.Unmarshal(b, &s) + if err != nil { + return err + } + + *dst = Text{String: s, Status: Present} + + return nil +} diff --git a/pgtype/varchar.go b/pgtype/varchar.go index 371efd7e..6be1a035 100644 --- a/pgtype/varchar.go +++ b/pgtype/varchar.go @@ -52,3 +52,7 @@ func (src *Varchar) Value() (driver.Value, error) { func (src *Varchar) MarshalJSON() ([]byte, error) { return (*Text)(src).MarshalJSON() } + +func (dst *Varchar) UnmarshalJSON(b []byte) error { + return (*Text)(dst).UnmarshalJSON(b) +}