github.com/newrelic/newrelic-client-go@v1.1.0/internal/serialization/map_string_interface.go (about) 1 package serialization 2 3 import ( 4 "encoding/json" 5 "strconv" 6 "strings" 7 ) 8 9 // MapStringInterface is used for custom unmarshaling of 10 // fields that have potentially dynamic types. 11 // E.g. when a field can be a string or an object/map 12 type MapStringInterface map[string]interface{} 13 type mapStringInterfaceProxy MapStringInterface 14 15 // UnmarshalJSON is a custom unmarshal method to guard against 16 // fields that can have more than one type returned from an API. 17 func (c *MapStringInterface) UnmarshalJSON(data []byte) error { 18 var mapStrInterface mapStringInterfaceProxy 19 20 str := string(data) 21 22 // Check for empty JSON string 23 if str == `""` { 24 return nil 25 } 26 27 // Remove quotes if this is a string representation of JSON 28 if strings.HasPrefix(str, "\"") && strings.HasSuffix(str, "\"") { 29 s, err := strconv.Unquote(str) 30 if err != nil { 31 return nil 32 } 33 34 data = []byte(s) 35 } 36 37 err := json.Unmarshal(data, &mapStrInterface) 38 if err != nil { 39 return err 40 } 41 42 *c = MapStringInterface(mapStrInterface) 43 44 return nil 45 }