json.go 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. // Copyright 2019 The etcd Authors
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package client
  15. import (
  16. "github.com/json-iterator/go"
  17. "github.com/modern-go/reflect2"
  18. "strconv"
  19. "unsafe"
  20. )
  21. type customNumberExtension struct {
  22. jsoniter.DummyExtension
  23. }
  24. func (cne *customNumberExtension) CreateDecoder(typ reflect2.Type) jsoniter.ValDecoder {
  25. if typ.String() == "interface {}" {
  26. return customNumberDecoder{}
  27. }
  28. return nil
  29. }
  30. type customNumberDecoder struct {
  31. }
  32. func (customNumberDecoder) Decode(ptr unsafe.Pointer, iter *jsoniter.Iterator) {
  33. switch iter.WhatIsNext() {
  34. case jsoniter.NumberValue:
  35. var number jsoniter.Number
  36. iter.ReadVal(&number)
  37. i64, err := strconv.ParseInt(string(number), 10, 64)
  38. if err == nil {
  39. *(*interface{})(ptr) = i64
  40. return
  41. }
  42. f64, err := strconv.ParseFloat(string(number), 64)
  43. if err == nil {
  44. *(*interface{})(ptr) = f64
  45. return
  46. }
  47. iter.ReportError("DecodeNumber", err.Error())
  48. default:
  49. *(*interface{})(ptr) = iter.Read()
  50. }
  51. }
  52. // caseSensitiveJsonIterator returns a jsoniterator API that's configured to be
  53. // case-sensitive when unmarshalling, and otherwise compatible with
  54. // the encoding/json standard library.
  55. func caseSensitiveJsonIterator() jsoniter.API {
  56. config := jsoniter.Config{
  57. EscapeHTML: true,
  58. SortMapKeys: true,
  59. ValidateJsonRawMessage: true,
  60. CaseSensitive: true,
  61. }.Froze()
  62. // Force jsoniter to decode number to interface{} via int64/float64, if possible.
  63. config.RegisterExtension(&customNumberExtension{})
  64. return config
  65. }