Skip to content

Instantly share code, notes, and snippets.

@jochasinga
Created November 5, 2015 01:55
Show Gist options
  • Save jochasinga/66e3f8109639dcbffd9c to your computer and use it in GitHub Desktop.
Save jochasinga/66e3f8109639dcbffd9c to your computer and use it in GitHub Desktop.
Pretty cool trick to map Go struct to and from arbitrary JSON
/* Original code posted here https://stackoverflow.com/questions/27492888/how-to-map-json-objects-with-dynamic-fields-to-go-structs */
package main
import (
"fmt"
"encoding/json"
"errors"
)
type Random struct {
CustomFields map[string]interface{}
}
func (r *Random) MarshalJSON() ([]byte, error) {
randmap := make(map[string]interface{})
// mapping the first-level JSON key
for k, v := range r.CustomFields {
randmap[k] = v
}
return json.Marshal(randmap)
}
func (r *Random) UnmarshalJSON(data []byte) error {
var randmap map[string]interface{}
if r == nil {
return errors.New("RawString: UnmarshalJSON on nil")
}
if err := json.Unmarshal(data, &randmap); err != nil {
return err
}
for k, v := range randmap {
r.CustomFields[k] = v
}
return nil
}
var uj = []byte(`{"name": "foo", "age": 300, "gigs": ["one", "two", 3.21]}`)
func main() {
r := Random{
CustomFields: map[string]interface{}{
"gaga": "ball",
"bambi": 2,
"darn": []interface{}{"one", 2, 3.0},
},
}
// Get a JSON from the Random struct
result, _ := r.MarshalJSON()
// This will unmarshal the uj blob to a map in CustomField
r.UnmarshalJSON(uj)
fmt.Println(string(result))
// marshal back to the struct
//r.UnmarshalJSON(result)
fmt.Println(r.CustomFields)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment