I have a Profile{}
struct with an ID
property of the type uuid.UUID
. When I marshal this, I am converting the UUID
to a string
, like this:
type Profile struct {
Id uuid.UUID
}
func (profile *Profile) MarshalJSON() ([]byte, error) {
type Alias Profile
return json.Marshal(&struct {
Id string
*Alias
}{
Id: profile.Id.String(),
Alias: (*Alias)(profile),
})
}
However, when I want to unmarshal this JSON, it complains that the id
is a string. So I need to initialise a UUID
struct when unmarshalling, like this: uuid.New([]byte(jsonId))
Is this possible to do without altering the UUID
implementation, and if so, how?
I'd suggest storing Id
as string instead of uuid.UUID
. Of course there are workarounds, but if you're not going to hold thousands of Profile
s in memory, you shouldn't notice any difference, and you'd be saving time dealing with serialization issues.
If you don't want that, check out the uuid
package you're using. Is the underlying type of UUID
really a string? If it's something else, like []byte
, just convert your string to []byte
before unmarshaling.
The idiomatic workaround would be what Not_a_Golfer commented under your question.