Created
March 4, 2016 18:57
-
-
Save davewalk/ea0fcd560843adb9efb2 to your computer and use it in GitHub Desktop.
Custom unmarhsaling of JSON example
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" | |
) | |
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