github.com/aws-cloudformation/cloudformation-cli-go-plugin@v1.2.0/cfn/encoding/encoding.go (about) 1 /* 2 Package encoding defines types and functions used for dealing with stringified-JSON. 3 */ 4 package encoding 5 6 import ( 7 "encoding/json" 8 "fmt" 9 "strconv" 10 ) 11 12 // String is a string type to be used when the default json marshaler/unmarshaler cannot be avoided 13 type String string 14 15 func NewString(ss string) *String { 16 s := String(ss) 17 return &s 18 } 19 20 func (s *String) Value() *string { 21 return (*string)(s) 22 } 23 24 func (s String) MarshalJSON() ([]byte, error) { 25 return json.Marshal(string(s)) 26 } 27 28 func (s *String) UnmarshalJSON(data []byte) error { 29 var ss string 30 err := json.Unmarshal(data, &ss) 31 if err != nil { 32 return err 33 } 34 35 *s = String(ss) 36 return nil 37 } 38 39 // Bool is a bool type to be used when the default json marshaler/unmarshaler cannot be avoided 40 type Bool bool 41 42 func NewBool(bb bool) *Bool { 43 b := Bool(bb) 44 return &b 45 } 46 47 func (b *Bool) Value() *bool { 48 return (*bool)(b) 49 } 50 51 func (b Bool) MarshalJSON() ([]byte, error) { 52 return json.Marshal(fmt.Sprint(bool(b))) 53 } 54 55 func (b *Bool) UnmarshalJSON(data []byte) error { 56 var s string 57 err := json.Unmarshal(data, &s) 58 if err != nil { 59 return err 60 } 61 62 val, err := strconv.ParseBool(s) 63 if err != nil { 64 return err 65 } 66 67 *b = Bool(val) 68 return nil 69 } 70 71 // Int is an int type to be used when the default json marshaler/unmarshaler cannot be avoided 72 type Int int64 73 74 func NewInt(ii int64) *Int { 75 i := Int(ii) 76 return &i 77 } 78 79 func (i *Int) Value() *int64 { 80 return (*int64)(i) 81 } 82 83 func (i Int) MarshalJSON() ([]byte, error) { 84 return json.Marshal(fmt.Sprint(int64(i))) 85 } 86 87 func (i *Int) UnmarshalJSON(data []byte) error { 88 var s string 89 err := json.Unmarshal(data, &s) 90 if err != nil { 91 return err 92 } 93 94 val, err := strconv.ParseInt(s, 0, 64) 95 if err != nil { 96 return err 97 } 98 99 *i = Int(val) 100 return nil 101 } 102 103 // Float is a float type to be used when the default json marshaler/unmarshaler cannot be avoided 104 type Float float64 105 106 func NewFloat(ff float64) *Float { 107 f := Float(ff) 108 return &f 109 } 110 111 func (f *Float) Value() *float64 { 112 return (*float64)(f) 113 } 114 115 func (f Float) MarshalJSON() ([]byte, error) { 116 return json.Marshal(fmt.Sprint(float64(f))) 117 } 118 119 func (f *Float) UnmarshalJSON(data []byte) error { 120 var s string 121 err := json.Unmarshal(data, &s) 122 if err != nil { 123 return err 124 } 125 126 val, err := strconv.ParseFloat(s, 64) 127 if err != nil { 128 return err 129 } 130 131 *f = Float(val) 132 return nil 133 }