当我尝试将[]字节编组为JSON格式时,我只得到一个奇怪的字符串.
请查看以下代码.
我有两个疑问:
如何将[]字节编组为JSON?
为什么[]字节成为这个字符串?
package main import ( "encoding/json" "fmt" "os" ) func main() { type ColorGroup struct { ByteSlice []byte SingleByte byte IntSlice []int } group := ColorGroup{ ByteSlice: []byte{0,0,0,1,2,3}, SingleByte: 10, IntSlice: []int{0,0,0,1,2,3}, } b, err := json.Marshal(group) if err != nil { fmt.Println("error:", err) } os.Stdout.Write(b) }
输出是:
{"ByteSlice":"AAAAAQID","SingleByte":10,"IntSlice":[0,0,0,1,2,3]}
golang playground:https://play.golang.org/p/wanppBGzNR
根据文档:https://golang.org/pkg/encoding/json/#Marshal
数组和切片值编码为JSON数组,但[]字节编码为base64编码的字符串,而nil切片编码为空JSON对象.
该值AAAAAQID
是字节切片的base64表示 - 例如
b, err := base64.StdEncoding.DecodeString("AAAAAQID") if err != nil { log.Fatal(err) } fmt.Printf("%v", b) // Outputs: [0 0 0 1 2 3]