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.

serder_test.go 1.3 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. package serder
  2. import (
  3. "testing"
  4. . "github.com/smartystreets/goconvey/convey"
  5. myreflect "gitlink.org.cn/cloudream/common/utils/reflect"
  6. )
  7. func Test_MapToObject(t *testing.T) {
  8. Convey("包含用字符串保存的int数据", t, func() {
  9. type Struct struct {
  10. A string `json:"a"`
  11. B int `json:"b"`
  12. C int64 `json:"c,string"`
  13. }
  14. mp := map[string]any{
  15. "a": "a",
  16. "b": 1,
  17. "c": "1234",
  18. }
  19. var st Struct
  20. err := MapToObject(mp, &st)
  21. So(err, ShouldBeNil)
  22. So(st.A, ShouldEqual, "a")
  23. So(st.B, ShouldEqual, 1)
  24. So(st.C, ShouldEqual, 1234)
  25. })
  26. }
  27. func Test_TypedMapToObject(t *testing.T) {
  28. type Struct struct {
  29. A string `json:"a"`
  30. B int `json:"b"`
  31. C int64 `json:"c,string"`
  32. }
  33. nameResovler := NewTypeNameResolver(true)
  34. nameResovler.Register(myreflect.GetGenericType[Struct]())
  35. Convey("结构体", t, func() {
  36. st := Struct{
  37. A: "a",
  38. B: 1,
  39. C: 2,
  40. }
  41. mp, err := ObjectToTypedMap(st, TypedSerderOption{
  42. TypeResolver: &nameResovler,
  43. TypeFieldName: "@type",
  44. })
  45. So(err, ShouldBeNil)
  46. st2Ptr, err := TypedMapToObject(mp, TypedSerderOption{
  47. TypeResolver: &nameResovler,
  48. TypeFieldName: "@type",
  49. })
  50. So(err, ShouldBeNil)
  51. st2, ok := st2Ptr.(Struct)
  52. So(ok, ShouldBeTrue)
  53. So(st2, ShouldHaveSameTypeAs, st)
  54. So(st2, ShouldResemble, st)
  55. })
  56. }

公共库

Contributors (1)