类似java中的LinkedHashMap,输出的json串是按key的插入顺序排序的
场景
一个java项目,重构为go某一个接口返回的数据结构是和客户端约定好的,有排序规则;返回结果是按key排序的一个map转成的字符串(java中可以直接用LinkedHashMap<String, Object>,然后转json)
源码
1 package main 2 3 import ( 4 "fmt" 5 "strings" 6 "encoding/json" 7 ) 8 9 type Smap []*SortMapNode 10 11 type SortMapNode struct { 12 Key string 13 Val interface{} 14 } 15 16 func (c *Smap) Put(key string, val interface{}) { 17 index, _, ok := c.get(key) 18 if ok { 19 (*c)[index].Val = val 20 } else { 21 node := &SortMapNode{Key: key, Val: val} 22 *c = append(*c, node) 23 } 24 } 25 26 func (c *Smap) Get(key string) (interface{}, bool) { 27 _, val, ok := c.get(key) 28 return val, ok 29 } 30 31 func (c *Smap) get(key string) (int, interface{}, bool) { 32 for index, node := range *c { 33 if node.Key == key { 34 return index, node.Val, true 35 } 36 } 37 return -1, nil, false 38 } 39 40 func ToSortedMapJson(smap *Smap) string { 41 s := "{" 42 for _, node := range *smap { 43 v := node.Val 44 isSamp := false 45 str := "" 46 switch v.(type){ 47 case *Smap: 48 isSamp = true 49 str = ToSortedMapJson(v.(*Smap)) 50 } 51 52 if(!isSamp){ 53 b, _ := json.Marshal(node.Val) 54 str = string(b) 55 } 56 57 s = fmt.Sprintf("%s\"%s\":%s,", s, node.Key, str) 58 } 59 s = strings.TrimRight(s, ",") 60 s = fmt.Sprintf("%s}", s) 61 return s 62 } 63 64 type testStruct struct{ 65 name string 66 value interface{} 67 } 68 69 func main(){ 70 smap := &Smap{} 71 72 n1 := []int{5, 6} 73 n2 := []string{"s3", "s4"} 74 n3 := []string{"s1", "s2"} 75 n4 := []interface{}{"a",5,6.7} 76 n4 = append(n4, "t") 77 n4 = append(n4, 1) 78 n4 = append(n4, 3.2) 79 80 s1 := &Smap{} 81 s1.Put("first", "1str") 82 s1.Put("second", "2str") 83 s1.Put("third", "3str") 84 85 s2 := &Smap{} 86 var t2 testStruct 87 t2.name = "testname" 88 t2.value = s2 89 s2.Put("s1", s1) 90 91 arr2 := []string{"str1", "str2"} 92 s2.Put("arr2", arr2) 93 94 smap.Put("1int", n1) 95 smap.Put("2string", n2) 96 smap.Put("3string", n3) 97 smap.Put("4interface", n4) 98 smap.Put("5smap", s1) 99 smap.Put("6interfaceSmap", s2) 100 101 s := ToSortedMapJson(smap) 102 fmt.Println(s) 103 }
运行结果(格式化后的json)
1 { 2 "1int": [5, 6], 3 "2string": ["s3", "s4"], 4 "3string": ["s1", "s2"], 5 "4interface": ["a", 5, 6.7, "t", 1, 3.2], 6 "5smap": { 7 "first": "1str", 8 "second": "2str", 9 "third": "3str" 10 }, 11 "6interfaceSmap": { 12 "s1": { 13 "first": "1str", 14 "second": "2str", 15 "third": "3str" 16 }, 17 "arr2": ["str1", "str2"] 18 } 19 }