将JSON [] byte封送为Go中的字符串 [英] Marshaling JSON []byte as strings in Go
问题描述
我有一个结构,其中包含要作为[] byte字段的字符串,我想将其编码为JSON.但是,生成的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()方法执行哪种转换? []字节编码的字符串.如何使用字符串{"Content":"Hello"}的原始内容生成JSON?
[]byte
被编组为base64编码的字符串.从文档:
数组和切片值编码为JSON数组,但
[]byte
编码为base64编码的字符串,而nil slice编码为空JSON对象.
未编组时,这些值会正确解码.
完成此操作的原因是JSON没有原始字节的本地表示形式.有关详细说明,请参见此问题. >
I have a struct containing strings as []byte fields which I'd like to encode into JSON. However, the generated JSON contains a non expected string representation of the slice contents. Here is an example of what I refer:
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))
}
This produces the following output:
Hello [72 101 108 108 111]
{"Content":"SGVsbG8="}
What kind of conversion is the json.Marshal() method performing to the []byte encoded string. How can I generate a JSON with the original content of my string {"Content":"Hello"}?
A []byte
is marshalled as base64 encoded string. From the documentation:
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 object.
These values are decoded properly when unmarshalled.
The reason why this is done is that JSON does not have a native representation for raw bytes. See this question for a detailed explanation.
这篇关于将JSON [] byte封送为Go中的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!