map按插入顺序排序后生成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)
}