1 package v1 2 3 import "encoding/json" 4 5 // UnmarshalJSON implements the json.Unmarshaller interface. 6 // If the value is a string, it sets the Value field of the StringSource. 7 // Otherwise, it is unmarshaled into the StringSourceSpec struct 8 func (s *StringSource) UnmarshalJSON(value []byte) error { 9 // If we can unmarshal to a simple string, just set the value 10 var simpleValue string 11 if err := json.Unmarshal(value, &simpleValue); err == nil { 12 s.Value = simpleValue 13 return nil 14 } 15 16 // Otherwise do the full struct unmarshal 17 return json.Unmarshal(value, &s.StringSourceSpec) 18 } 19 20 // MarshalJSON implements the json.Marshaller interface. 21 // If the StringSource contains only a string Value (or is empty), it is marshaled as a JSON string. 22 // Otherwise, the StringSourceSpec struct is marshaled as a JSON object. 23 func (s *StringSource) MarshalJSON() ([]byte, error) { 24 // If we have only a cleartext value set, do a simple string marshal 25 if s.StringSourceSpec == (StringSourceSpec{Value: s.Value}) { 26 return json.Marshal(s.Value) 27 } 28 29 // Otherwise do the full struct marshal of the externalized bits 30 return json.Marshal(s.StringSourceSpec) 31 } 32