map按插入顺序排序后生成json

  1. package main
  2. import (
  3. "fmt"
  4. "strings"
  5. "encoding/json"
  6. )
  7. type Smap []*SortMapNode
  8. type SortMapNode struct {
  9. Key string
  10. Val interface{}
  11. }
  12. func (c *Smap) Put(key string, val interface{}) {
  13. index, _, ok := c.get(key)
  14. if ok {
  15. (*c)[index].Val = val
  16. } else {
  17. node := &SortMapNode{Key: key, Val: val}
  18. *c = append(*c, node)
  19. }
  20. }
  21. func (c *Smap) Get(key string) (interface{}, bool) {
  22. _, val, ok := c.get(key)
  23. return val, ok
  24. }
  25. func (c *Smap) get(key string) (int, interface{}, bool) {
  26. for index, node := range *c {
  27. if node.Key == key {
  28. return index, node.Val, true
  29. }
  30. }
  31. return -1, nil, false
  32. }
  33. func ToSortedMapJson(smap *Smap) string {
  34. s := "{"
  35. for _, node := range *smap {
  36. v := node.Val
  37. isSamp := false
  38. str := ""
  39. switch v.(type){
  40. case *Smap:
  41. isSamp = true
  42. str = ToSortedMapJson(v.(*Smap))
  43. }
  44. if(!isSamp){
  45. b, _ := json.Marshal(node.Val)
  46. str = string(b)
  47. }
  48. s = fmt.Sprintf("%s\"%s\":%s,", s, node.Key, str)
  49. }
  50. s = strings.TrimRight(s, ",")
  51. s = fmt.Sprintf("%s}", s)
  52. return s
  53. }
  54. type testStruct struct{
  55. name string
  56. value interface{}
  57. }
  58. func main(){
  59. smap := &Smap{}
  60. n1 := []int{5, 6}
  61. n2 := []string{"s3", "s4"}
  62. n3 := []string{"s1", "s2"}
  63. n4 := []interface{}{"a",5,6.7}
  64. n4 = append(n4, "t")
  65. n4 = append(n4, 1)
  66. n4 = append(n4, 3.2)
  67. s1 := &Smap{}
  68. s1.Put("first", "1str")
  69. s1.Put("second", "2str")
  70. s1.Put("third", "3str")
  71. s2 := &Smap{}
  72. var t2 testStruct
  73. t2.name = "testname"
  74. t2.value = s2
  75. s2.Put("s1", s1)
  76. arr2 := []string{"str1", "str2"}
  77. s2.Put("arr2", arr2)
  78. smap.Put("1int", n1)
  79. smap.Put("2string", n2)
  80. smap.Put("3string", n3)
  81. smap.Put("4interface", n4)
  82. smap.Put("5smap", s1)
  83. smap.Put("6interfaceSmap", s2)
  84. s := ToSortedMapJson(smap)
  85. fmt.Println(s)
  86. }