Instantly share code, notes, and snippets.

@0rka /.go
Last active Jul 13, 2017

Embed
What would you like to do?
Unmarshalling JSON structs containing interfaces in Go
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