unmarshal.go 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228
  1. package jsonutil
  2. import (
  3. "encoding/base64"
  4. "encoding/json"
  5. "fmt"
  6. "io"
  7. "reflect"
  8. "time"
  9. "github.com/aws/aws-sdk-go/aws"
  10. "github.com/aws/aws-sdk-go/private/protocol"
  11. )
  12. // UnmarshalJSON reads a stream and unmarshals the results in object v.
  13. func UnmarshalJSON(v interface{}, stream io.Reader) error {
  14. var out interface{}
  15. err := json.NewDecoder(stream).Decode(&out)
  16. if err == io.EOF {
  17. return nil
  18. } else if err != nil {
  19. return err
  20. }
  21. return unmarshalAny(reflect.ValueOf(v), out, "")
  22. }
  23. func unmarshalAny(value reflect.Value, data interface{}, tag reflect.StructTag) error {
  24. vtype := value.Type()
  25. if vtype.Kind() == reflect.Ptr {
  26. vtype = vtype.Elem() // check kind of actual element type
  27. }
  28. t := tag.Get("type")
  29. if t == "" {
  30. switch vtype.Kind() {
  31. case reflect.Struct:
  32. // also it can't be a time object
  33. if _, ok := value.Interface().(*time.Time); !ok {
  34. t = "structure"
  35. }
  36. case reflect.Slice:
  37. // also it can't be a byte slice
  38. if _, ok := value.Interface().([]byte); !ok {
  39. t = "list"
  40. }
  41. case reflect.Map:
  42. // cannot be a JSONValue map
  43. if _, ok := value.Interface().(aws.JSONValue); !ok {
  44. t = "map"
  45. }
  46. }
  47. }
  48. switch t {
  49. case "structure":
  50. if field, ok := vtype.FieldByName("_"); ok {
  51. tag = field.Tag
  52. }
  53. return unmarshalStruct(value, data, tag)
  54. case "list":
  55. return unmarshalList(value, data, tag)
  56. case "map":
  57. return unmarshalMap(value, data, tag)
  58. default:
  59. return unmarshalScalar(value, data, tag)
  60. }
  61. }
  62. func unmarshalStruct(value reflect.Value, data interface{}, tag reflect.StructTag) error {
  63. if data == nil {
  64. return nil
  65. }
  66. mapData, ok := data.(map[string]interface{})
  67. if !ok {
  68. return fmt.Errorf("JSON value is not a structure (%#v)", data)
  69. }
  70. t := value.Type()
  71. if value.Kind() == reflect.Ptr {
  72. if value.IsNil() { // create the structure if it's nil
  73. s := reflect.New(value.Type().Elem())
  74. value.Set(s)
  75. value = s
  76. }
  77. value = value.Elem()
  78. t = t.Elem()
  79. }
  80. // unwrap any payloads
  81. if payload := tag.Get("payload"); payload != "" {
  82. field, _ := t.FieldByName(payload)
  83. return unmarshalAny(value.FieldByName(payload), data, field.Tag)
  84. }
  85. for i := 0; i < t.NumField(); i++ {
  86. field := t.Field(i)
  87. if field.PkgPath != "" {
  88. continue // ignore unexported fields
  89. }
  90. // figure out what this field is called
  91. name := field.Name
  92. if locName := field.Tag.Get("locationName"); locName != "" {
  93. name = locName
  94. }
  95. member := value.FieldByIndex(field.Index)
  96. err := unmarshalAny(member, mapData[name], field.Tag)
  97. if err != nil {
  98. return err
  99. }
  100. }
  101. return nil
  102. }
  103. func unmarshalList(value reflect.Value, data interface{}, tag reflect.StructTag) error {
  104. if data == nil {
  105. return nil
  106. }
  107. listData, ok := data.([]interface{})
  108. if !ok {
  109. return fmt.Errorf("JSON value is not a list (%#v)", data)
  110. }
  111. if value.IsNil() {
  112. l := len(listData)
  113. value.Set(reflect.MakeSlice(value.Type(), l, l))
  114. }
  115. for i, c := range listData {
  116. err := unmarshalAny(value.Index(i), c, "")
  117. if err != nil {
  118. return err
  119. }
  120. }
  121. return nil
  122. }
  123. func unmarshalMap(value reflect.Value, data interface{}, tag reflect.StructTag) error {
  124. if data == nil {
  125. return nil
  126. }
  127. mapData, ok := data.(map[string]interface{})
  128. if !ok {
  129. return fmt.Errorf("JSON value is not a map (%#v)", data)
  130. }
  131. if value.IsNil() {
  132. value.Set(reflect.MakeMap(value.Type()))
  133. }
  134. for k, v := range mapData {
  135. kvalue := reflect.ValueOf(k)
  136. vvalue := reflect.New(value.Type().Elem()).Elem()
  137. unmarshalAny(vvalue, v, "")
  138. value.SetMapIndex(kvalue, vvalue)
  139. }
  140. return nil
  141. }
  142. func unmarshalScalar(value reflect.Value, data interface{}, tag reflect.StructTag) error {
  143. switch d := data.(type) {
  144. case nil:
  145. return nil // nothing to do here
  146. case string:
  147. switch value.Interface().(type) {
  148. case *string:
  149. value.Set(reflect.ValueOf(&d))
  150. case []byte:
  151. b, err := base64.StdEncoding.DecodeString(d)
  152. if err != nil {
  153. return err
  154. }
  155. value.Set(reflect.ValueOf(b))
  156. case *time.Time:
  157. format := tag.Get("timestampFormat")
  158. if len(format) == 0 {
  159. format = protocol.ISO8601TimeFormatName
  160. }
  161. t, err := protocol.ParseTime(format, d)
  162. if err != nil {
  163. return err
  164. }
  165. value.Set(reflect.ValueOf(&t))
  166. case aws.JSONValue:
  167. // No need to use escaping as the value is a non-quoted string.
  168. v, err := protocol.DecodeJSONValue(d, protocol.NoEscape)
  169. if err != nil {
  170. return err
  171. }
  172. value.Set(reflect.ValueOf(v))
  173. default:
  174. return fmt.Errorf("unsupported value: %v (%s)", value.Interface(), value.Type())
  175. }
  176. case float64:
  177. switch value.Interface().(type) {
  178. case *int64:
  179. di := int64(d)
  180. value.Set(reflect.ValueOf(&di))
  181. case *float64:
  182. value.Set(reflect.ValueOf(&d))
  183. case *time.Time:
  184. // Time unmarshaled from a float64 can only be epoch seconds
  185. t := time.Unix(int64(d), 0).UTC()
  186. value.Set(reflect.ValueOf(&t))
  187. default:
  188. return fmt.Errorf("unsupported value: %v (%s)", value.Interface(), value.Type())
  189. }
  190. case bool:
  191. switch value.Interface().(type) {
  192. case *bool:
  193. value.Set(reflect.ValueOf(&d))
  194. default:
  195. return fmt.Errorf("unsupported value: %v (%s)", value.Interface(), value.Type())
  196. }
  197. default:
  198. return fmt.Errorf("unsupported JSON value (%v)", data)
  199. }
  200. return nil
  201. }