You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

config.go 1.4 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. package json
  2. import (
  3. "reflect"
  4. jsoniter "github.com/json-iterator/go"
  5. "gitlink.org.cn/cloudream/common/pkgs/types"
  6. )
  7. type Config struct {
  8. unionHandler *UnionHandler
  9. exts []jsoniter.Extension
  10. }
  11. func New() *Config {
  12. return &Config{
  13. unionHandler: &UnionHandler{
  14. internallyTagged: make(map[reflect.Type]*anyTypeUnionInternallyTagged),
  15. externallyTagged: make(map[reflect.Type]*anyTypeUnionExternallyTagged),
  16. },
  17. }
  18. }
  19. func (c *Config) UseUnionInternallyTagged(u *types.AnyTypeUnion, tagField string) *Config {
  20. iu := &anyTypeUnionInternallyTagged{
  21. Union: u,
  22. TagField: tagField,
  23. TagToType: make(map[string]reflect.Type),
  24. }
  25. for _, eleType := range u.ElementTypes {
  26. iu.Add(eleType)
  27. }
  28. c.unionHandler.internallyTagged[u.UnionType] = iu
  29. return c
  30. }
  31. func (c *Config) UseUnionExternallyTagged(u *types.AnyTypeUnion) *Config {
  32. eu := &anyTypeUnionExternallyTagged{
  33. Union: u,
  34. TypeNameToType: make(map[string]reflect.Type),
  35. }
  36. for _, eleType := range u.ElementTypes {
  37. eu.Add(eleType)
  38. }
  39. c.unionHandler.externallyTagged[u.UnionType] = eu
  40. return c
  41. }
  42. func (c *Config) UseExtension(ext jsoniter.Extension) *Config {
  43. c.exts = append(c.exts, ext)
  44. return c
  45. }
  46. func (c *Config) Build() Serder {
  47. cfg := jsoniter.Config{}
  48. api := cfg.Froze()
  49. api.RegisterExtension(c.unionHandler)
  50. for _, ext := range c.exts {
  51. api.RegisterExtension(ext)
  52. }
  53. return Serder{
  54. cfg: *c,
  55. api: api,
  56. }
  57. }