将切片对象序列化为 JSON 会产生乱码

Serialising slice object to JSON creates gibberish

以下代码将 Go 切片序列化为 JSON:

package main

import (
    "encoding/json"
    "fmt"
)

type FooType uint8

const (
    Zero  FooType = 0
    One   FooType = 1
    Two   FooType = 2
    Three FooType = 3
)

func main() {
    var fooSlice []FooType
    fooSlice = make([]FooType, 1)
    fooSlice[0] = One
    bs, _ := json.Marshal(fooSlice)
    fmt.Println(string(bs))
}

输出:

"AQ=="

我正在努力实现的目标以及我希望打印的内容如下:

"[1]"

这是怎么回事?

这里有一些简单的例子:

package main

import (
   "encoding/json"
   "strings"
)

func main() {
   { // example 1
      b := new(strings.Builder)
      json.NewEncoder(b).Encode([]uint8{1})
      println(b.String() == "\"AQ==\"\n")
   }
   { // example 2
      b := new(strings.Builder)
      json.NewEncoder(b).Encode([]byte{1})
      println(b.String() == "\"AQ==\"\n")
   }
}

和文档:

Array and slice values encode as JSON arrays, except that []byte encodes as a base64-encoded string, and a nil slice encodes as the null JSON value.

https://golang.org/pkg/encoding/json#Marshal