0

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?

Patrick Reck
  • 329
  • 2
  • 4
  • 16
  • 2
    You can create your own marshalable/unmarshalable UUID type by wrapping the UUID, as seen in this example: http://stackoverflow.com/questions/23695479/format-timestamp-in-outgoing-json-in-golang – Not_a_Golfer Dec 30 '15 at 12:11
  • 1
    Which package are you using? If [this one](https://godoc.org/code.google.com/p/go-uuid/uuid) then it already implements `json.Marshaler` and `json.Unmarshaler`. – Ainar-G Dec 30 '15 at 13:02

1 Answers1

0

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 Profiles 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.

Zippo
  • 15,850
  • 10
  • 60
  • 58