map按插入顺序排序后生成json
类似java中的LinkedHashMap,输出的json串是按key的插入顺序排序的
场景
一个java项目,重构为go 某一个接口返回的数据结构是和客户端约定好的,有排序规则;返回结果是按key插入顺序进行排序的一个map转成的字符串(java中可以直接用LinkedHashMap,然后转json)
package main import ( "fmt" "strings" "encoding/json" ) type Smap []*SortMapNode type SortMapNode struct { Key string Val interface{} } func (c *Smap) Put(key string, val interface{}) { index, _, ok := c.get(key) if ok { (*c)[index].Val = val } else { node := &SortMapNode{Key: key, Val: val} *c = append(*c, node) } } func (c *Smap) Get(key string) (interface{}, bool) { _, val, ok := c.get(key) return val, ok } func (c *Smap) get(key string) (int, interface{}, bool) { for index, node := range *c { if node.Key == key { return index, node.Val, true } } return -1, nil, false } func ToSortedMapJson(smap *Smap) string { s := "{" for _, node := range *smap { v := node.Val isSamp := false str := "" switch v.(type){ case *Smap: isSamp = true str = ToSortedMapJson(v.(*Smap)) } if(!isSamp){ b, _ := json.Marshal(node.Val) str = string(b) } s = fmt.Sprintf("%s\"%s\":%s,", s, node.Key, str) } s = strings.TrimRight(s, ",") s = fmt.Sprintf("%s}", s) return s } type testStruct struct{ name string value interface{} } func main(){ smap := &Smap{} n1 := []int{5, 6} n2 := []string{"s3", "s4"} n3 := []string{"s1", "s2"} n4 := []interface{}{"a",5,6.7} n4 = append(n4, "t") n4 = append(n4, 1) n4 = append(n4, 3.2) s1 := &Smap{} s1.Put("first", "1str") s1.Put("second", "2str") s1.Put("third", "3str") s2 := &Smap{} var t2 testStruct t2.name = "testname" t2.value = s2 s2.Put("s1", s1) arr2 := []string{"str1", "str2"} s2.Put("arr2", arr2) smap.Put("1int", n1) smap.Put("2string", n2) smap.Put("3string", n3) smap.Put("4interface", n4) smap.Put("5smap", s1) smap.Put("6interfaceSmap", s2) s := ToSortedMapJson(smap) fmt.Println(s) }
example
smap := &Smap{} smap.Put("name", "myname") smap.Put("attr", "123") s := ToSortedMapJson(smap) fmt.Println(s)
结果输出
{ "1int": [5, 6], "2string": ["s3", "s4"], "3string": ["s1", "s2"], "4interface": ["a", 5, 6.7, "t", 1, 3.2], "5smap": { "first": "1str", "second": "2str", "third": "3str" }, "6interfaceSmap": { "s1": { "first": "1str", "second": "2str", "third": "3str" }, "arr2": ["str1", "str2"] } }