Skip to content

Instantly share code, notes, and snippets.

@davewalk
Created March 4, 2016 18:57
Show Gist options
  • Save davewalk/ea0fcd560843adb9efb2 to your computer and use it in GitHub Desktop.
Save davewalk/ea0fcd560843adb9efb2 to your computer and use it in GitHub Desktop.
Custom unmarhsaling of JSON example
package main
import (
"encoding/json"
"fmt"
)
type Record struct {
SiteId string `json:"site_id"`
JsonData interface{} `json:"json_data"`
}
func (r *Record) UnmarshalJSON(b []byte) (err error) {
type TempRecord struct {
SiteId string `json:"site_id"`
JsonData string `json:"json_data"`
}
var temp TempRecord
err = json.Unmarshal(b, &temp)
if err != nil {
return
}
r.SiteId = temp.SiteId
var j interface{}
err = json.Unmarshal([]byte(temp.JsonData), &j)
if err != nil {
return
}
r.JsonData = j
return
}
func main() {
msg := []byte(`{"site_id": "823", "json_data": "{\"color\": \"white\", \"price\": 35.43}"}`)
var r Record
err := json.Unmarshal(msg, &r)
if err != nil {
fmt.Println(err)
}
fmt.Println(r)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment