以下代码将 Go slice 序列化为 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 anil
slice encodes as thenull
JSON value.
关于json - 将 slice 对象序列化为 JSON 会产生乱码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66615986/