【发布时间】:2016-07-27 16:17:19
【问题描述】:
我有一个包含字符串的结构,我想将其编码为 JSON 的 []byte 字段。但是,生成的 JSON 包含切片内容的非预期字符串表示。这是我所指的一个例子:
package main
import (
"fmt"
"encoding/json"
)
type Msg struct {
Content []byte
}
func main() {
helloStr := "Hello"
helloSlc := []byte(helloStr)
fmt.Println(helloStr, helloSlc)
obj := Msg{helloSlc}
json, _ := json.Marshal(obj)
fmt.Println(string(json))
}
这会产生以下输出:
Hello [72 101 108 108 111]
{"Content":"SGVsbG8="}
json.Marshal() 方法对 []byte 编码的字符串执行什么样的转换。如何使用我的字符串 {"Content":"Hello"} 的原始内容生成 JSON?
【问题讨论】: