gofrs / uuid

A UUID package for Go
MIT License
1.57k stars 110 forks source link

UnmarshalJSON for UUID #73

Closed JoelPagliuca closed 5 years ago

JoelPagliuca commented 5 years ago

I see NullUUID has an UnmarshalJSON capability, is there any reason one hasn't been implemented for UUID? I imagine this should have the same implementation as UnmarshallText

Super keen to use this package for an API but struggling to unmarshal POST JSON content

acln0 commented 5 years ago

Since uuid.UUID implements encoding.TextUnmarhsaler, per the encoding/json documentation, the method will be used to unmarshal a JSON string:

Otherwise, if the value implements encoding.TextUnmarshaler and the input is a JSON quoted string, Unmarshal calls that value's UnmarshalText method with the unquoted form of the string.

This program demonstrates the behavior, which seems to be correct:

package main

import (
    "encoding/json"
    "fmt"
    "log"

    "github.com/gofrs/uuid"
)

var data = `{ "x": 42, "y": true, "uuid": "6ba7b8109dad11d180b400c04fd430c8" }`

type Foo struct {
    X    int
    Y    bool
    UUID uuid.UUID
}

func main() {
    var f Foo
    if err := json.Unmarshal([]byte(data), &f); err != nil {
        log.Fatal(err)
    }
    fmt.Printf("%+v\n", f)
}
JoelPagliuca commented 5 years ago

I was using json.NewDecoder(r.Body).Decode(&objectWithUUID)

Switching to json.Unmarshal() worked, thanks for the response :)