下面的代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | package main import ( "encoding/json" "fmt" ) type Foo struct { Number int `json:"number"` Title string `json:"title"` } func main() { datas := make(map[int]Foo) for i := 0; i < 10; i++ { datas[i] = Foo{Number: 1, Title: "test"} } jsonString, _ := json.Marshal(datas) fmt.Println(string(jsonString)) } |
运行结果啥也没输出,一个空行。
将map的键改成字符串:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | package main import ( "encoding/json" "fmt" "strconv" ) type Foo struct { Number int `json:"number"` Title string `json:"title"` } func main() { datas := make(map[string]Foo) for i := 0; i < 10; i++ { datas[strconv.Itoa(i)] = Foo{Number: 1, Title: "test"} } jsonString, _ := json.Marshal(datas) fmt.Println(string(jsonString)) } |
输出:
{“0”:{“number”:1,”title”:”test”},”1″:{“number”:1,”title”:”test”},”2″:{“number”:1,”title”:”test”},”3″:{“number”:1,”title”:”test”},”4″:{“number”:1,”title”:”test”},”5″:{“number”:1,”title”:”test”},”6″:{“number”:1,”title”:”test”},”7″:{“number”:1,”title”:”test”},”8″:{“number”:1,”title”:”test”},”9″:{“number”:1,”title”:”test”}}