Skip to content

Instantly share code, notes, and snippets.

@andremedeiros
Created April 16, 2019 14:28
Show Gist options
  • Save andremedeiros/927837f428e0df549aee14499b402411 to your computer and use it in GitHub Desktop.
Save andremedeiros/927837f428e0df549aee14499b402411 to your computer and use it in GitHub Desktop.
package main
import (
"fmt"
"encoding/json"
)
type Thing1 struct {}
func (Thing1) DoThing() {}
type Thing2 struct {
Number int `json:"number"`
String string `json:"string"`
}
func (Thing2) DoThing() {}
type Bleh interface {
DoThing()
}
type Holder struct {
Type string `json:"type"`
Doer Bleh
}
func (h *Holder) UnmarshalJSON(data []byte) error {
type Alias Holder
aux := &struct {
*Alias
}{
Alias: (*Alias)(h),
}
if err := json.Unmarshal(data, &aux); err != nil {
return err
}
switch aux.Type {
case "Thing1":
aux.Doer = &Thing1{}
case "Thing2":
aux.Doer = &Thing2{}
}
envelope := &struct {
Payload Bleh
}{
Payload: aux.Doer,
}
if err := json.Unmarshal(data, &envelope); err != nil {
return err
}
h.Doer = envelope.Payload
return nil
}
func main() {
payload := `{
"type": "Thing2",
"payload": {
"number": 42,
"string": "once upon a time in a galaxy far far away"
}
}`
h := &Holder{}
if err := json.Unmarshal([]byte(payload), h); err != nil {
fmt.Println(err)
}
fmt.Println(h)
fmt.Println(h.Doer)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment