Last active
August 29, 2015 14:11
-
-
Save r10r/2438ee08a43ada6ec97c to your computer and use it in GitHub Desktop.
Implement MarshalJSON for type alias.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"encoding/json" | |
"fmt" | |
) | |
type Metadata struct { | |
UUID string | |
Name string | |
} | |
type Collection struct { | |
Name string | |
Metadata Metadata | |
} | |
type AliasedMetadata Metadata | |
type AliasedCollection struct { | |
Name string | |
Metadata AliasedMetadata | |
} | |
func (m Metadata) MarshalJSON() ([]byte, error) { | |
return []byte(fmt.Sprintf("\"%s\"", m.UUID)), nil | |
} | |
func (m AliasedMetadata) MarshalJSON() ([]byte, error) { | |
return []byte(fmt.Sprintf("\"%s-%s\"", m.Name, m.UUID)), nil | |
} | |
func toJSON(col interface{}) { | |
out, err := json.Marshal(col) | |
if err != nil { | |
panic(err) | |
} | |
fmt.Println(string(out)) | |
} | |
func main() { | |
col := Collection{ | |
Name: "MyCollection", | |
Metadata: Metadata{UUID: "12345", Name: "MyMetadata"}, | |
} | |
toJSON(col) | |
col2 := AliasedCollection{ | |
Name: "MyCollection", | |
Metadata: AliasedMetadata{UUID: "12345", Name: "MyAliasedMetadata"}, | |
} | |
toJSON(col2) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment