Skip to content

Commit

Permalink
player: Support JSON unmarshal for class.
Browse files Browse the repository at this point in the history
  • Loading branch information
dennwc committed Feb 9, 2024
1 parent 629f4ef commit d8e570c
Showing 1 changed file with 28 additions and 2 deletions.
30 changes: 28 additions & 2 deletions player/class.go
Original file line number Diff line number Diff line change
@@ -1,9 +1,14 @@
package player

import "encoding/json"
import (
"encoding/json"
"fmt"
"strings"
)

var (
_ json.Marshaler = Class(0)
_ json.Marshaler = Class(0)
_ json.Unmarshaler = (*Class)(nil)
)

const (
Expand All @@ -30,3 +35,24 @@ func (c Class) String() string {
func (c Class) MarshalJSON() ([]byte, error) {
return json.Marshal(c.String())
}

func (c *Class) UnmarshalJSON(data []byte) error {
var s string
if err := json.Unmarshal(data, &s); err != nil {
return err
}
s = strings.ToLower(s)
switch s {
case "":
*c = 0
case "warrior":
*c = Warrior
case "wizard":
*c = Wizard
case "conjurer":
*c = Conjurer
default:
return fmt.Errorf("invalid class: %q", s)
}
return nil
}

0 comments on commit d8e570c

Please sign in to comment.