summaryrefslogtreecommitdiffstats
path: root/Godeps/_workspace/src/github.com/huandu/facebook/result.go
blob: fd760be4eb1e10ebc887701d5289682df568ac84 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
// A facebook graph api client in go.
// https://github.com/huandu/facebook/
//
// Copyright 2012 - 2015, Huan Du
// Licensed under the MIT license
// https://github.com/huandu/facebook/blob/master/LICENSE

package facebook

import (
	"bytes"
	"encoding/json"
	"fmt"
	"net/http"
	"reflect"
	"runtime"
	"strconv"
	"strings"
	"time"
)

// MakeResult makes a Result from facebook Graph API response.
func MakeResult(jsonBytes []byte) (Result, error) {
	res := Result{}
	err := makeResult(jsonBytes, &res)

	if err != nil {
		return nil, err
	}

	// facebook may return an error
	return res, res.Err()
}

func makeResult(jsonBytes []byte, res interface{}) error {
	if bytes.Equal(jsonBytes, facebookSuccessJsonBytes) {
		return nil
	}

	jsonReader := bytes.NewReader(jsonBytes)
	dec := json.NewDecoder(jsonReader)

	// issue #19
	// app_scoped user_id in a post-Facebook graph 2.0 would exceeds 2^53.
	// use Number instead of float64 to avoid precision lost.
	dec.UseNumber()

	err := dec.Decode(res)

	if err != nil {
		typ := reflect.TypeOf(res)

		if typ != nil {
			// if res is a slice, jsonBytes may be a facebook error.
			// try to decode it as Error.
			kind := typ.Kind()

			if kind == reflect.Ptr {
				typ = typ.Elem()
				kind = typ.Kind()
			}

			if kind == reflect.Array || kind == reflect.Slice {
				var errRes Result
				err = makeResult(jsonBytes, &errRes)

				if err != nil {
					return err
				}

				err = errRes.Err()

				if err == nil {
					err = fmt.Errorf("cannot format facebook response. expect an array but get an object.")
				}

				return err
			}
		}

		return fmt.Errorf("cannot format facebook response. %v", err)
	}

	return nil
}

// Get gets a field from Result.
//
// Field can be a dot separated string.
// If field name is "a.b.c", it will try to return value of res["a"]["b"]["c"].
//
// To access array items, use index value in field.
// For instance, field "a.0.c" means to read res["a"][0]["c"].
//
// It doesn't work with Result which has a key contains dot. Use GetField in this case.
//
// Returns nil if field doesn't exist.
func (res Result) Get(field string) interface{} {
	if field == "" {
		return res
	}

	f := strings.Split(field, ".")
	return res.get(f)
}

// GetField gets a field from Result.
//
// Arguments are treated as keys to access value in Result.
// If arguments are "a","b","c", it will try to return value of res["a"]["b"]["c"].
//
// To access array items, use index value as a string.
// For instance, args of "a", "0", "c" means to read res["a"][0]["c"].
//
// Returns nil if field doesn't exist.
func (res Result) GetField(fields ...string) interface{} {
	if len(fields) == 0 {
		return res
	}

	return res.get(fields)
}

func (res Result) get(fields []string) interface{} {
	v, ok := res[fields[0]]

	if !ok || v == nil {
		return nil
	}

	if len(fields) == 1 {
		return v
	}

	value := getValueField(reflect.ValueOf(v), fields[1:])

	if !value.IsValid() {
		return nil
	}

	return value.Interface()
}

func getValueField(value reflect.Value, fields []string) reflect.Value {
	valueType := value.Type()
	kind := valueType.Kind()
	field := fields[0]

	switch kind {
	case reflect.Array, reflect.Slice:
		// field must be a number.
		n, err := strconv.ParseUint(field, 10, 0)

		if err != nil {
			return reflect.Value{}
		}

		if n >= uint64(value.Len()) {
			return reflect.Value{}
		}

		// work around a reflect package pitfall.
		value = reflect.ValueOf(value.Index(int(n)).Interface())

	case reflect.Map:
		v := value.MapIndex(reflect.ValueOf(field))

		if !v.IsValid() {
			return v
		}

		// get real value type.
		value = reflect.ValueOf(v.Interface())

	default:
		return reflect.Value{}
	}

	if len(fields) == 1 {
		return value
	}

	return getValueField(value, fields[1:])
}

// Decode decodes full result to a struct.
// It only decodes fields defined in the struct.
//
// As all facebook response fields are lower case strings,
// Decode will convert all camel-case field names to lower case string.
// e.g. field name "FooBar" will be converted to "foo_bar".
// The side effect is that if a struct has 2 fields with only capital
// differences, decoder will map these fields to a same result value.
//
// If a field is missing in the result, Decode keeps it unchanged by default.
//
// Decode can read struct field tag value to change default behavior.
//
// Examples:
//
//     type Foo struct {
//         // "id" must exist in response. note the leading comma.
//         Id string `facebook:",required"`
//
//         // use "name" as field name in response.
//         TheName string `facebook:"name"`
//     }
//
// To change default behavior, set a struct tag `facebook:",required"` to fields
// should not be missing.
//
// Returns error if v is not a struct or any required v field name absents in res.
func (res Result) Decode(v interface{}) (err error) {
	defer func() {
		if r := recover(); r != nil {
			if _, ok := r.(runtime.Error); ok {
				panic(r)
			}

			err = r.(error)
		}
	}()

	err = res.decode(reflect.ValueOf(v), "")
	return
}

// DecodeField decodes a field of result to any type, including struct.
// Field name format is defined in Result.Get().
//
// More details about decoding struct see Result.Decode().
func (res Result) DecodeField(field string, v interface{}) error {
	f := res.Get(field)

	if f == nil {
		return fmt.Errorf("field '%v' doesn't exist in result.", field)
	}

	return decodeField(reflect.ValueOf(f), reflect.ValueOf(v), field)
}

// Err returns an error if Result is a Graph API error.
//
// The returned error can be converted to Error by type assertion.
//     err := res.Err()
//     if err != nil {
//         if e, ok := err.(*Error); ok {
//             // read more details in e.Message, e.Code and e.Type
//         }
//     }
//
// For more information about Graph API Errors, see
// https://developers.facebook.com/docs/reference/api/errors/
func (res Result) Err() error {
	var err Error
	e := res.DecodeField("error", &err)

	// no "error" in result. result is not an error.
	if e != nil {
		return nil
	}

	// code may be missing in error.
	// assign a non-zero value to it.
	if err.Code == 0 {
		err.Code = ERROR_CODE_UNKNOWN
	}

	return &err
}

// Paging creates a PagingResult for this Result and
// returns error if the Result cannot be used for paging.
//
// Facebook uses following JSON structure to response paging information.
// If "data" doesn't present in Result, Paging will return error.
//     {
//         "data": [...],
//         "paging": {
//             "previous": "https://graph.facebook.com/...",
//             "next": "https://graph.facebook.com/..."
//         }
//     }
func (res Result) Paging(session *Session) (*PagingResult, error) {
	return newPagingResult(session, res)
}

// Batch creates a BatchResult for this result and
// returns error if the Result is not a batch api response.
//
// See BatchApi document for a sample usage.
func (res Result) Batch() (*BatchResult, error) {
	return newBatchResult(res)
}

// DebugInfo creates a DebugInfo for this result if this result
// has "__debug__" key.
func (res Result) DebugInfo() *DebugInfo {
	var info Result
	err := res.DecodeField(debugInfoKey, &info)

	if err != nil {
		return nil
	}

	debugInfo := &DebugInfo{}
	info.DecodeField("messages", &debugInfo.Messages)

	if proto, ok := info[debugProtoKey]; ok {
		if v, ok := proto.(string); ok {
			debugInfo.Proto = v
		}
	}

	if header, ok := info[debugHeaderKey]; ok {
		if v, ok := header.(http.Header); ok {
			debugInfo.Header = v

			debugInfo.FacebookApiVersion = v.Get(facebookApiVersionHeader)
			debugInfo.FacebookDebug = v.Get(facebookDebugHeader)
			debugInfo.FacebookRev = v.Get(facebookRevHeader)
		}
	}

	return debugInfo
}

func (res Result) decode(v reflect.Value, fullName string) error {
	for v.Kind() == reflect.Ptr || v.Kind() == reflect.Interface {
		v = v.Elem()
	}

	if v.Kind() != reflect.Struct {
		return fmt.Errorf("output value must be a struct.")
	}

	if !v.CanSet() {
		return fmt.Errorf("output value cannot be set.")
	}

	if fullName != "" {
		fullName += "."
	}

	var field reflect.Value
	var name, fbTag string
	var val interface{}
	var ok, required bool
	var err error

	vType := v.Type()
	num := vType.NumField()

	for i := 0; i < num; i++ {
		name = ""
		required = false
		field = v.Field(i)
		fbTag = vType.Field(i).Tag.Get("facebook")

		// parse struct field tag
		if fbTag != "" {
			index := strings.IndexRune(fbTag, ',')

			if index == -1 {
				name = fbTag
			} else {
				name = fbTag[:index]

				if fbTag[index:] == ",required" {
					required = true
				}
			}
		}

		if name == "" {
			name = camelCaseToUnderScore(v.Type().Field(i).Name)
		}

		val, ok = res[name]

		if !ok {
			// check whether the field is required. if so, report error.
			if required {
				return fmt.Errorf("cannot find field '%v%v' in result.", fullName, name)
			}

			continue
		}

		if err = decodeField(reflect.ValueOf(val), field, fmt.Sprintf("%v%v", fullName, name)); err != nil {
			return err
		}
	}

	return nil
}

func decodeField(val reflect.Value, field reflect.Value, fullName string) error {
	if field.Kind() == reflect.Ptr {
		// reset Ptr field if val is nil.
		if !val.IsValid() {
			if !field.IsNil() && field.CanSet() {
				field.Set(reflect.Zero(field.Type()))
			}

			return nil
		}

		if field.IsNil() {
			field.Set(reflect.New(field.Type().Elem()))
		}

		field = field.Elem()
	}

	if !field.CanSet() {
		return fmt.Errorf("field '%v' cannot be decoded. make sure the output value is able to be set.", fullName)
	}

	if !val.IsValid() {
		return fmt.Errorf("field '%v' is not a pointer. cannot assign nil to it.", fullName)
	}

	kind := field.Kind()
	valType := val.Type()

	switch kind {
	case reflect.Bool:
		if valType.Kind() == reflect.Bool {
			field.SetBool(val.Bool())
		} else {
			return fmt.Errorf("field '%v' is not a bool in result.", fullName)
		}

	case reflect.Int8:
		switch valType.Kind() {
		case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
			n := val.Int()

			if n < -128 || n > 127 {
				return fmt.Errorf("field '%v' value exceeds the range of int8.", fullName)
			}

			field.SetInt(int64(n))

		case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
			n := val.Uint()

			if n > 127 {
				return fmt.Errorf("field '%v' value exceeds the range of int8.", fullName)
			}

			field.SetInt(int64(n))

		case reflect.Float32, reflect.Float64:
			n := val.Float()

			if n < -128 || n > 127 {
				return fmt.Errorf("field '%v' value exceeds the range of int8.", fullName)
			}

			field.SetInt(int64(n))

		case reflect.String:
			// only json.Number is allowed to be used as number.
			if val.Type() != typeOfJSONNumber {
				return fmt.Errorf("field '%v' value is string, not a number.", fullName)
			}

			n, err := strconv.ParseInt(val.String(), 10, 8)

			if err != nil {
				return fmt.Errorf("field '%v' value is not a valid int8.", fullName)
			}

			field.SetInt(n)

		default:
			return fmt.Errorf("field '%v' is not an integer in result.", fullName)
		}

	case reflect.Int16:
		switch valType.Kind() {
		case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
			n := val.Int()

			if n < -32768 || n > 32767 {
				return fmt.Errorf("field '%v' value exceeds the range of int16.", fullName)
			}

			field.SetInt(int64(n))

		case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
			n := val.Uint()

			if n > 32767 {
				return fmt.Errorf("field '%v' value exceeds the range of int16.", fullName)
			}

			field.SetInt(int64(n))

		case reflect.Float32, reflect.Float64:
			n := val.Float()

			if n < -32768 || n > 32767 {
				return fmt.Errorf("field '%v' value exceeds the range of int16.", fullName)
			}

			field.SetInt(int64(n))

		case reflect.String:
			// only json.Number is allowed to be used as number.
			if val.Type() != typeOfJSONNumber {
				return fmt.Errorf("field '%v' value is string, not a number.", fullName)
			}

			n, err := strconv.ParseInt(val.String(), 10, 16)

			if err != nil {
				return fmt.Errorf("field '%v' value is not a valid int16.", fullName)
			}

			field.SetInt(n)

		default:
			return fmt.Errorf("field '%v' is not an integer in result.", fullName)
		}

	case reflect.Int32:
		switch valType.Kind() {
		case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
			n := val.Int()

			if n < -2147483648 || n > 2147483647 {
				return fmt.Errorf("field '%v' value exceeds the range of int32.", fullName)
			}

			field.SetInt(int64(n))

		case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
			n := val.Uint()

			if n > 2147483647 {
				return fmt.Errorf("field '%v' value exceeds the range of int32.", fullName)
			}

			field.SetInt(int64(n))

		case reflect.Float32, reflect.Float64:
			n := val.Float()

			if n < -2147483648 || n > 2147483647 {
				return fmt.Errorf("field '%v' value exceeds the range of int32.", fullName)
			}

			field.SetInt(int64(n))

		case reflect.String:
			// only json.Number is allowed to be used as number.
			if val.Type() != typeOfJSONNumber {
				return fmt.Errorf("field '%v' value is string, not a number.", fullName)
			}

			n, err := strconv.ParseInt(val.String(), 10, 32)

			if err != nil {
				return fmt.Errorf("field '%v' value is not a valid int32.", fullName)
			}

			field.SetInt(n)

		default:
			return fmt.Errorf("field '%v' is not an integer in result.", fullName)
		}

	case reflect.Int64:
		switch valType.Kind() {
		case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
			n := val.Int()
			field.SetInt(n)

		case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
			n := val.Uint()

			if n > 9223372036854775807 {
				return fmt.Errorf("field '%v' value exceeds the range of int64.", fullName)
			}

			field.SetInt(int64(n))

		case reflect.Float32, reflect.Float64:
			n := val.Float()

			if n < -9223372036854775808 || n > 9223372036854775807 {
				return fmt.Errorf("field '%v' value exceeds the range of int64.", fullName)
			}

			field.SetInt(int64(n))

		case reflect.String:
			// only json.Number is allowed to be used as number.
			if val.Type() != typeOfJSONNumber {
				return fmt.Errorf("field '%v' value is string, not a number.", fullName)
			}

			n, err := strconv.ParseInt(val.String(), 10, 64)

			if err != nil {
				return fmt.Errorf("field '%v' value is not a valid int64.", fullName)
			}

			field.SetInt(n)

		default:
			return fmt.Errorf("field '%v' is not an integer in result.", fullName)
		}

	case reflect.Int:
		bits := field.Type().Bits()

		var min, max int64

		if bits == 32 {
			min = -2147483648
			max = 2147483647
		} else if bits == 64 {
			min = -9223372036854775808
			max = 9223372036854775807
		}

		switch valType.Kind() {
		case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
			n := val.Int()

			if n < min || n > max {
				return fmt.Errorf("field '%v' value exceeds the range of int.", fullName)
			}

			field.SetInt(int64(n))

		case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
			n := val.Uint()

			if n > uint64(max) {
				return fmt.Errorf("field '%v' value exceeds the range of int.", fullName)
			}

			field.SetInt(int64(n))

		case reflect.Float32, reflect.Float64:
			n := val.Float()

			if n < float64(min) || n > float64(max) {
				return fmt.Errorf("field '%v' value exceeds the range of int.", fullName)
			}

			field.SetInt(int64(n))

		case reflect.String:
			// only json.Number is allowed to be used as number.
			if val.Type() != typeOfJSONNumber {
				return fmt.Errorf("field '%v' value is string, not a number.", fullName)
			}

			n, err := strconv.ParseInt(val.String(), 10, bits)

			if err != nil {
				return fmt.Errorf("field '%v' value is not a valid int%v.", fullName, bits)
			}

			field.SetInt(n)

		default:
			return fmt.Errorf("field '%v' is not an integer in result.", fullName)
		}

	case reflect.Uint8:
		switch valType.Kind() {
		case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
			n := val.Int()

			if n < 0 || n > 0xFF {
				return fmt.Errorf("field '%v' value exceeds the range of uint8.", fullName)
			}

			field.SetUint(uint64(n))

		case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
			n := val.Uint()

			if n > 0xFF {
				return fmt.Errorf("field '%v' value exceeds the range of uint8.", fullName)
			}

			field.SetUint(uint64(n))

		case reflect.Float32, reflect.Float64:
			n := val.Float()

			if n < 0 || n > 0xFF {
				return fmt.Errorf("field '%v' value exceeds the range of uint8.", fullName)
			}

			field.SetUint(uint64(n))

		case reflect.String:
			// only json.Number is allowed to be used as number.
			if val.Type() != typeOfJSONNumber {
				return fmt.Errorf("field '%v' value is string, not a number.", fullName)
			}

			n, err := strconv.ParseUint(val.String(), 10, 8)

			if err != nil {
				return fmt.Errorf("field '%v' value is not a valid uint8.", fullName)
			}

			field.SetUint(n)

		default:
			return fmt.Errorf("field '%v' is not an integer in result.", fullName)
		}

	case reflect.Uint16:
		switch valType.Kind() {
		case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
			n := val.Int()

			if n < 0 || n > 0xFFFF {
				return fmt.Errorf("field '%v' value exceeds the range of uint16.", fullName)
			}

			field.SetUint(uint64(n))

		case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
			n := val.Uint()

			if n > 0xFFFF {
				return fmt.Errorf("field '%v' value exceeds the range of uint16.", fullName)
			}

			field.SetUint(uint64(n))

		case reflect.Float32, reflect.Float64:
			n := val.Float()

			if n < 0 || n > 0xFFFF {
				return fmt.Errorf("field '%v' value exceeds the range of uint16.", fullName)
			}

			field.SetUint(uint64(n))

		case reflect.String:
			// only json.Number is allowed to be used as number.
			if val.Type() != typeOfJSONNumber {
				return fmt.Errorf("field '%v' value is string, not a number.", fullName)
			}

			n, err := strconv.ParseUint(val.String(), 10, 16)

			if err != nil {
				return fmt.Errorf("field '%v' value is not a valid uint16.", fullName)
			}

			field.SetUint(n)

		default:
			return fmt.Errorf("field '%v' is not an integer in result.", fullName)
		}

	case reflect.Uint32:
		switch valType.Kind() {
		case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
			n := val.Int()

			if n < 0 || n > 0xFFFFFFFF {
				return fmt.Errorf("field '%v' value exceeds the range of uint32.", fullName)
			}

			field.SetUint(uint64(n))

		case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
			n := val.Uint()

			if n > 0xFFFFFFFF {
				return fmt.Errorf("field '%v' value exceeds the range of uint32.", fullName)
			}

			field.SetUint(uint64(n))

		case reflect.Float32, reflect.Float64:
			n := val.Float()

			if n < 0 || n > 0xFFFFFFFF {
				return fmt.Errorf("field '%v' value exceeds the range of uint32.", fullName)
			}

			field.SetUint(uint64(n))

		case reflect.String:
			// only json.Number is allowed to be used as number.
			if val.Type() != typeOfJSONNumber {
				return fmt.Errorf("field '%v' value is string, not a number.", fullName)
			}

			n, err := strconv.ParseUint(val.String(), 10, 32)

			if err != nil {
				return fmt.Errorf("field '%v' value is not a valid uint32.", fullName)
			}

			field.SetUint(n)

		default:
			return fmt.Errorf("field '%v' is not an integer in result.", fullName)
		}

	case reflect.Uint64:
		switch valType.Kind() {
		case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
			n := val.Int()

			if n < 0 {
				return fmt.Errorf("field '%v' value exceeds the range of uint64.", fullName)
			}

			field.SetUint(uint64(n))

		case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
			n := val.Uint()
			field.SetUint(n)

		case reflect.Float32, reflect.Float64:
			n := val.Float()

			if n < 0 || n > 0xFFFFFFFFFFFFFFFF {
				return fmt.Errorf("field '%v' value exceeds the range of uint64.", fullName)
			}

			field.SetUint(uint64(n))

		case reflect.String:
			// only json.Number is allowed to be used as number.
			if val.Type() != typeOfJSONNumber {
				return fmt.Errorf("field '%v' value is string, not a number.", fullName)
			}

			n, err := strconv.ParseUint(val.String(), 10, 64)

			if err != nil {
				return fmt.Errorf("field '%v' value is not a valid uint64.", fullName)
			}

			field.SetUint(n)

		default:
			return fmt.Errorf("field '%v' is not an integer in result.", fullName)
		}

	case reflect.Uint:
		bits := field.Type().Bits()

		var max uint64

		if bits == 32 {
			max = 0xFFFFFFFF
		} else if bits == 64 {
			max = 0xFFFFFFFFFFFFFFFF
		}

		switch valType.Kind() {
		case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
			n := val.Int()

			if n < 0 || uint64(n) > max {
				return fmt.Errorf("field '%v' value exceeds the range of uint.", fullName)
			}

			field.SetUint(uint64(n))

		case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
			n := val.Uint()

			if n > max {
				return fmt.Errorf("field '%v' value exceeds the range of uint.", fullName)
			}

			field.SetUint(uint64(n))

		case reflect.Float32, reflect.Float64:
			n := val.Float()

			if n < 0 || n > float64(max) {
				return fmt.Errorf("field '%v' value exceeds the range of uint.", fullName)
			}

			field.SetUint(uint64(n))

		case reflect.String:
			// only json.Number is allowed to be used as number.
			if val.Type() != typeOfJSONNumber {
				return fmt.Errorf("field '%v' value is string, not a number.", fullName)
			}

			n, err := strconv.ParseUint(val.String(), 10, bits)

			if err != nil {
				return fmt.Errorf("field '%v' value is not a valid uint%v.", fullName, bits)
			}

			field.SetUint(n)

		default:
			return fmt.Errorf("field '%v' is not an integer in result.", fullName)
		}

	case reflect.Float32, reflect.Float64:
		switch valType.Kind() {
		case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
			n := val.Int()
			field.SetFloat(float64(n))

		case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
			n := val.Uint()
			field.SetFloat(float64(n))

		case reflect.Float32, reflect.Float64:
			n := val.Float()
			field.SetFloat(n)

		case reflect.String:
			// only json.Number is allowed to be used as number.
			if val.Type() != typeOfJSONNumber {
				return fmt.Errorf("field '%v' value is string, not a number.", fullName)
			}

			n, err := strconv.ParseFloat(val.String(), 64)

			if err != nil {
				return fmt.Errorf("field '%v' is not a valid float64.", fullName)
			}

			field.SetFloat(n)

		default:
			return fmt.Errorf("field '%v' is not a float in result.", fullName)
		}

	case reflect.String:
		if valType.Kind() != reflect.String {
			return fmt.Errorf("field '%v' is not a string in result.", fullName)
		}

		field.SetString(val.String())

	case reflect.Struct:
		if field.Type().ConvertibleTo(typeOfTime) {
			if valType.Kind() != reflect.String {
				return fmt.Errorf("field '%v' is not a string in result.", fullName)
			}

			t, err := time.Parse("2006-01-02T15:04:05-0700", val.String())

			if err != nil {
				return fmt.Errorf("field '%v' was unable to parse the time string '%s'.", fullName, val.String())
			}

			matchedType := reflect.ValueOf(t).Convert(field.Type())
			field.Set(matchedType)
			return nil
		}

		if valType.Kind() != reflect.Map || valType.Key().Kind() != reflect.String {
			return fmt.Errorf("field '%v' is not a json object in result.", fullName)
		}

		// safe convert val to Result. type assertion doesn't work in this case.
		var r Result
		reflect.ValueOf(&r).Elem().Set(val)

		if err := r.decode(field, fullName); err != nil {
			return err
		}

	case reflect.Map:
		if valType.Kind() != reflect.Map || valType.Key().Kind() != reflect.String {
			return fmt.Errorf("field '%v' is not a json object in result.", fullName)
		}

		// map key must be string
		if field.Type().Key().Kind() != reflect.String {
			return fmt.Errorf("field '%v' in struct is a map with non-string key type. it's not allowed.", fullName)
		}

		var needAddr bool
		valueType := field.Type().Elem()

		// shortcut for map[string]interface{}.
		if valueType.Kind() == reflect.Interface {
			field.Set(val)
			break
		}

		if field.IsNil() {
			field.Set(reflect.MakeMap(field.Type()))
		}

		if valueType.Kind() == reflect.Ptr {
			valueType = valueType.Elem()
			needAddr = true
		}

		for _, key := range val.MapKeys() {
			// val.MapIndex(key) returns a Value with wrong type.
			// use following trick to get correct Value.
			value := reflect.ValueOf(val.MapIndex(key).Interface())
			newValue := reflect.New(valueType)

			if err := decodeField(value, newValue, fmt.Sprintf("%v.%v", fullName, key)); err != nil {
				return err
			}

			if needAddr {
				field.SetMapIndex(key, newValue)
			} else {
				field.SetMapIndex(key, newValue.Elem())
			}
		}

	case reflect.Slice, reflect.Array:
		if valType.Kind() != reflect.Slice && valType.Kind() != reflect.Array {
			return fmt.Errorf("field '%v' is not a json array in result.", fullName)
		}

		valLen := val.Len()

		if kind == reflect.Array {
			if field.Len() < valLen {
				return fmt.Errorf("cannot copy all field '%v' values to struct. expected len is %v. actual len is %v.",
					fullName, field.Len(), valLen)
			}
		}

		var slc reflect.Value
		var needAddr bool

		valueType := field.Type().Elem()

		// shortcut for array of interface
		if valueType.Kind() == reflect.Interface {
			if kind == reflect.Array {
				for i := 0; i < valLen; i++ {
					field.Index(i).Set(val.Index(i))
				}
			} else { // kind is slice
				field.Set(val)
			}

			break
		}

		if kind == reflect.Array {
			slc = field.Slice(0, valLen)
		} else {
			// kind is slice
			slc = reflect.MakeSlice(field.Type(), valLen, valLen)
			field.Set(slc)
		}

		if valueType.Kind() == reflect.Ptr {
			needAddr = true
			valueType = valueType.Elem()
		}

		for i := 0; i < valLen; i++ {
			// val.Index(i) returns a Value with wrong type.
			// use following trick to get correct Value.
			valIndexValue := reflect.ValueOf(val.Index(i).Interface())
			newValue := reflect.New(valueType)

			if err := decodeField(valIndexValue, newValue, fmt.Sprintf("%v.%v", fullName, i)); err != nil {
				return err
			}

			if needAddr {
				slc.Index(i).Set(newValue)
			} else {
				slc.Index(i).Set(newValue.Elem())
			}
		}

	default:
		return fmt.Errorf("field '%v' in struct uses unsupported type '%v'.", fullName, kind)
	}

	return nil
}