json - 将 slice 对象序列化为 JSON 会产生乱码

标签 json go slice

以下代码将 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 a nil slice encodes as the null JSON value.

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

关于json - 将 slice 对象序列化为 JSON 会产生乱码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66615986/

相关文章:

go - 在 go 中对错误进行分组的最佳方法是什么?

python - 基于多索引列数据框中的一系列列进行切片

Java gson 通用数组/列表反序列化

将普通旧 CLR 对象序列化为 JSON 的 C# 代码

javascript - 合并多个具有相同id的json

python - Pandas - 将大数据框切成 block

pointers - 附加到作为 map 中值的 slice

json - Go - 将通用结构传递给函数

已有字节缓冲区 slice 时的 Golang Reader 接口(interface)实现

go - 在 Go 中如何从结构的 slice 中删除一个项目