simplejson_go11.go 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. // +build go1.1
  2. package simplejson
  3. import (
  4. "bytes"
  5. "encoding/json"
  6. "errors"
  7. "io"
  8. "reflect"
  9. "strconv"
  10. )
  11. // Implements the json.Unmarshaler interface.
  12. func (j *Json) UnmarshalJSON(p []byte) error {
  13. dec := json.NewDecoder(bytes.NewBuffer(p))
  14. dec.UseNumber()
  15. return dec.Decode(&j.data)
  16. }
  17. // NewFromReader returns a *Json by decoding from an io.Reader
  18. func NewFromReader(r io.Reader) (*Json, error) {
  19. j := new(Json)
  20. dec := json.NewDecoder(r)
  21. dec.UseNumber()
  22. err := dec.Decode(&j.data)
  23. return j, err
  24. }
  25. // Float64 coerces into a float64
  26. func (j *Json) Float64() (float64, error) {
  27. switch j.data.(type) {
  28. case json.Number:
  29. return j.data.(json.Number).Float64()
  30. case float32, float64:
  31. return reflect.ValueOf(j.data).Float(), nil
  32. case int, int8, int16, int32, int64:
  33. return float64(reflect.ValueOf(j.data).Int()), nil
  34. case uint, uint8, uint16, uint32, uint64:
  35. return float64(reflect.ValueOf(j.data).Uint()), nil
  36. }
  37. return 0, errors.New("invalid value type")
  38. }
  39. // Int coerces into an int
  40. func (j *Json) Int() (int, error) {
  41. switch j.data.(type) {
  42. case json.Number:
  43. i, err := j.data.(json.Number).Int64()
  44. return int(i), err
  45. case float32, float64:
  46. return int(reflect.ValueOf(j.data).Float()), nil
  47. case int, int8, int16, int32, int64:
  48. return int(reflect.ValueOf(j.data).Int()), nil
  49. case uint, uint8, uint16, uint32, uint64:
  50. return int(reflect.ValueOf(j.data).Uint()), nil
  51. }
  52. return 0, errors.New("invalid value type")
  53. }
  54. // Int64 coerces into an int64
  55. func (j *Json) Int64() (int64, error) {
  56. switch j.data.(type) {
  57. case json.Number:
  58. return j.data.(json.Number).Int64()
  59. case float32, float64:
  60. return int64(reflect.ValueOf(j.data).Float()), nil
  61. case int, int8, int16, int32, int64:
  62. return reflect.ValueOf(j.data).Int(), nil
  63. case uint, uint8, uint16, uint32, uint64:
  64. return int64(reflect.ValueOf(j.data).Uint()), nil
  65. }
  66. return 0, errors.New("invalid value type")
  67. }
  68. // Uint64 coerces into an uint64
  69. func (j *Json) Uint64() (uint64, error) {
  70. switch j.data.(type) {
  71. case json.Number:
  72. return strconv.ParseUint(j.data.(json.Number).String(), 10, 64)
  73. case float32, float64:
  74. return uint64(reflect.ValueOf(j.data).Float()), nil
  75. case int, int8, int16, int32, int64:
  76. return uint64(reflect.ValueOf(j.data).Int()), nil
  77. case uint, uint8, uint16, uint32, uint64:
  78. return reflect.ValueOf(j.data).Uint(), nil
  79. }
  80. return 0, errors.New("invalid value type")
  81. }