unmarshal.go 4.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213
  1. package jsonutil
  2. import (
  3. "encoding/base64"
  4. "encoding/json"
  5. "fmt"
  6. "io"
  7. "io/ioutil"
  8. "reflect"
  9. "time"
  10. )
  11. // UnmarshalJSON reads a stream and unmarshals the results in object v.
  12. func UnmarshalJSON(v interface{}, stream io.Reader) error {
  13. var out interface{}
  14. b, err := ioutil.ReadAll(stream)
  15. if err != nil {
  16. return err
  17. }
  18. if len(b) == 0 {
  19. return nil
  20. }
  21. if err := json.Unmarshal(b, &out); err != nil {
  22. return err
  23. }
  24. return unmarshalAny(reflect.ValueOf(v), out, "")
  25. }
  26. func unmarshalAny(value reflect.Value, data interface{}, tag reflect.StructTag) error {
  27. vtype := value.Type()
  28. if vtype.Kind() == reflect.Ptr {
  29. vtype = vtype.Elem() // check kind of actual element type
  30. }
  31. t := tag.Get("type")
  32. if t == "" {
  33. switch vtype.Kind() {
  34. case reflect.Struct:
  35. // also it can't be a time object
  36. if _, ok := value.Interface().(*time.Time); !ok {
  37. t = "structure"
  38. }
  39. case reflect.Slice:
  40. // also it can't be a byte slice
  41. if _, ok := value.Interface().([]byte); !ok {
  42. t = "list"
  43. }
  44. case reflect.Map:
  45. t = "map"
  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. errf := func() error {
  144. return fmt.Errorf("unsupported value: %v (%s)", value.Interface(), value.Type())
  145. }
  146. switch d := data.(type) {
  147. case nil:
  148. return nil // nothing to do here
  149. case string:
  150. switch value.Interface().(type) {
  151. case *string:
  152. value.Set(reflect.ValueOf(&d))
  153. case []byte:
  154. b, err := base64.StdEncoding.DecodeString(d)
  155. if err != nil {
  156. return err
  157. }
  158. value.Set(reflect.ValueOf(b))
  159. default:
  160. return errf()
  161. }
  162. case float64:
  163. switch value.Interface().(type) {
  164. case *int64:
  165. di := int64(d)
  166. value.Set(reflect.ValueOf(&di))
  167. case *float64:
  168. value.Set(reflect.ValueOf(&d))
  169. case *time.Time:
  170. t := time.Unix(int64(d), 0).UTC()
  171. value.Set(reflect.ValueOf(&t))
  172. default:
  173. return errf()
  174. }
  175. case bool:
  176. switch value.Interface().(type) {
  177. case *bool:
  178. value.Set(reflect.ValueOf(&d))
  179. default:
  180. return errf()
  181. }
  182. default:
  183. return fmt.Errorf("unsupported JSON value (%v)", data)
  184. }
  185. return nil
  186. }