Debian Codegraph @

simplejson_go10.go

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