Unmarshaling JSON to UUID type
I am trying to use the json.Unmarshaler interface to unbind the UUID in a uuid.UUID field in a structure. I created a custom type myUUID and everything works until I try to access the methods that are usually found on uuid.UUID. How can I handle this? I'm relatively new to Go, so maybe I don't quite understand custom types yet.
package main
import (
"encoding/json"
"errors"
"fmt"
"code.google.com/p/go-uuid/uuid"
)
var jsonstring = `
{
"uuid": "273b62ad-a99d-48be-8d80-ccc55ef688b4"
}
`
type myUUID uuid.UUID
type Data struct {
uuid myUUID
}
func (u *myUUID) UnmarshalJson(b []byte) error {
id := uuid.Parse(string(b[:]))
if id == nil {
return errors.New("Could not parse UUID")
}
*u = myUUID(id)
return nil
}
func main() {
d := new(Data)
err := json.Unmarshal([]byte(jsonstring), &d)
if err != nil {
fmt.Printf("%s", err)
}
fmt.Println(d.uuid.String())
}
source to share
Go to custom types do not inherit methods . I refactored the code with a custom framework and included UnmarshalJSON.
type ServiceID struct {
UUID uuid.UUID
}
type Meta struct {
Name string `json:"name"`
Version string `json:"version"`
SID *ServiceID `json:"UUID"`
}
func (self *ServiceID) UnmarshalJSON(b []byte) error {
s := strings.Trim(string(b), "\"")
self.UUID = uuid.Parse(s)
if self.UUID == nil {
return errors.New("Could not parse UUID")
}
return nil
}
source to share
You might want to make sure your variable myuuid
is visible / exported to Data struct
: as in "public".
Same for type alias myuuid
(instead of myuuid
)
type MyUUID uuid.UUID
type Data struct {
Uuid MyUUID
}
From JSON and Go :
The json package only accesses the exported fields of struct types (those that start with an uppercase letter).
As Ainar G commented , also recommends:
Words in names that are initialisms or abbreviations (such as "
URL
" or "NATO
") have a consistent case.
For example, "URL
" should appear as "URL
" or "URL
" (as in "urlPony
", or "urlPony
"), never as "URL
". Here's an example:ServeHTTP
notServeHTTP
.This rule also applies to "
ID
" when it is not sufficient for an "identifier", so write "appID
" instead of "appID
".
In your case, this would mean:
type Data struct {
UUID MyUUID
}
source to share