-
-
Save 0rka/79528674c3f38aeb00ef72d213f32d64 to your computer and use it in GitHub Desktop.
Unmarshalling JSON structs containing interfaces in Go
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" | |
"time" | |
) | |
type Playable interface { | |
Play() error | |
} | |
type Movie struct { | |
Title string `json:"title"` | |
Length int `json:"length"` | |
} | |
func (m *Movie) Play() error { | |
time.Sleep(time.Duration(m.Length) * time.Minute) | |
return nil | |
} | |
type Playables []Playable | |
type TVGuide struct { | |
Company string `json:"company"` | |
Notices string `json:"notices"` | |
ID string `json:"id"` | |
Library Playables `json:"library"` | |
} | |
func (p *Playables) UnmarshalJSON(b []byte) error { | |
var LibraryFields map[string]*json.RawMessage | |
if err := json.Unmarshal(b, &LibraryFields); err != nil { | |
return err | |
} | |
for LFKey, LFValue := range LibraryFields { | |
if LFKey == "movies" { | |
var LibraryMovies []*json.RawMessage | |
if err := json.Unmarshal(*LFValue, &LibraryMovies); err != nil { | |
return err | |
} | |
for _, LibraryMovie := range LibraryMovies { | |
var movie Movie | |
if err := json.Unmarshal(*LibraryMovie, &movie); err != nil { | |
return err | |
} | |
*p = append(*p, &movie) | |
} | |
} | |
} | |
return nil | |
} | |
func main() { | |
myjson := []byte(`{"company":"0rkaTV","notices":"NO RUNNING WITH SCISSORS","id":"0x1337H4X0R","library":{"movies":[{"title":"Titanic","length":194},{"title":"Matrix","length":150}]}}`) | |
var OrkaTVGuide TVGuide | |
if err := json.Unmarshal(myjson, &OrkaTVGuide); err != nil { | |
fmt.Println(err) | |
} | |
fmt.Println(OrkaTVGuide) | |
fmt.Println("Hello, playground") | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment