Closed JoelPagliuca closed 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)
}
I was using json.NewDecoder(r.Body).Decode(&objectWithUUID)
Switching to json.Unmarshal()
worked, thanks for the response :)
I see
NullUUID
has anUnmarshalJSON
capability, is there any reason one hasn't been implemented forUUID
? I imagine this should have the same implementation asUnmarshallText
Super keen to use this package for an API but struggling to unmarshal POST JSON content