Last active
December 30, 2022 10:44
-
-
Save odeke-em/a2f0ad491c5d097e1ea29ecd036644a5 to your computer and use it in GitHub Desktop.
Example on custom UnmarshalJSON and MarshalJSON
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" | |
"log" | |
"strconv" | |
"strings" | |
) | |
type Animal uint | |
const ( | |
CommonAnimal Animal = iota | |
Zebra | |
Gopher | |
) | |
func (a *Animal) String() string { | |
switch *a { | |
case Gopher: | |
return "gopher" | |
case Zebra: | |
return "zebra" | |
default: | |
return "common-animal" | |
} | |
} | |
func sToAnimal(s string) Animal { | |
switch strings.ToLower(s) { | |
case "gopher": | |
return Gopher | |
case "zebra": | |
return Zebra | |
default: | |
return CommonAnimal | |
} | |
} | |
func (a *Animal) UnmarshalJSON(b []byte) error { | |
unquoted, err := strconv.Unquote(string(b)) | |
if err != nil { | |
return nil | |
} | |
aAnimal := sToAnimal(unquoted) | |
*a = aAnimal | |
return nil | |
} | |
func (a *Animal) MarshalJSON() ([]byte, error) { | |
quoted := strconv.Quote(a.String()) | |
return []byte(quoted), nil | |
} | |
func Example_marshalJSON() { | |
zoo := []Animal{Gopher, Zebra, CommonAnimal, Gopher, Gopher, Zebra} | |
marshaled, err := json.Marshal(&zoo) | |
if err != nil { | |
log.Fatal(err) | |
} | |
fmt.Printf("%s", marshaled) | |
// Output: | |
// ["gopher","zebra","common-animal","gopher","gopher","zebra"] | |
} | |
func Example_unmarshalJSON() { | |
rawZooManifest := `["zebra", "zebra", "common-animal", "gopher", "gopher"]` | |
var zooManifest []*Animal | |
if err := json.Unmarshal([]byte(rawZooManifest), &zooManifest); err != nil { | |
log.Fatal(err) | |
} | |
fmt.Printf("%+v", zooManifest) | |
// Output: | |
// [zebra zebra common-animal gopher gopher] | |
} | |
func main() { | |
Example_unmarshalJSON() | |
Example_marshalJSON() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment