如何在 Go 中将 byte/uint8 数组编组为 json 数组? [英] How to marshal a byte/uint8 array as json array in Go?
问题描述
我有一个带有 []uint8
成员的结构,我用 json.Marshal
编写它.问题是,它将 uint8
s 解释为 char
s 并输出一个字符串而不是一个数字数组.
I've got a struct with a []uint8
member and I'm writing it with json.Marshal
. Trouble is, it's interpreting the uint8
s as char
s and it outputs a string rather than an array of numbers.
如果它是 []int
,我可以让它工作,但如果我可以避免它,我不想分配和复制项目.我可以吗?
I can get this to work if it's a []int
, but I don't want to have to allocate and copy over the items if I can avoid it. Can I?
推荐答案
根据 docs,[]byte
将被编码为 Base64 字符串.
According to the docs, a []byte
will be encoded as a Base64 string.
数组和切片值编码为 JSON 数组,除了 []byte 编码为 base64 编码字符串,而 nil 切片编码为空 JSON 对象."em>
"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."
所以我认为你可能需要让你的结构实现 Marshaler 接口通过实现您自己的 MarshalJSON
方法,从您的 []uint8
中生成更理想的 JSON 数组编码.
So I think that you may need to make your struct implement the Marshaler interface by implementing your own MarshalJSON
method that makes a more desirable JSON array encoding out of your []uint8
.
以这个例子为例:
import "fmt"
import "encoding/json"
import "strings"
type Test struct {
Name string
Array []uint8
}
func (t *Test) MarshalJSON() ([]byte, error) {
var array string
if t.Array == nil {
array = "null"
} else {
array = strings.Join(strings.Fields(fmt.Sprintf("%d", t.Array)), ",")
}
jsonResult := fmt.Sprintf(`{"Name":%q,"Array":%s}`, t.Name, array)
return []byte(jsonResult), nil
}
func main() {
t := &Test{"Go", []uint8{'h', 'e', 'l', 'l', 'o'}}
m, err := json.Marshal(t)
if err != nil {
fmt.Println(err)
}
fmt.Printf("%s", m) // {"Name":"Go","Array":[104,101,108,108,111]}
}
http://play.golang.org/p/Tip59Z9gqs
或者也许更好的主意是创建一个以 []uint8
作为其基础类型的新类型,将该类型设为 Marshaler
,并在该类型中使用该类型你的结构.
Or maybe a better idea would be to make a new type that has []uint8
as its underlying type, make that type a Marshaler
, and use that type in your struct.
import "fmt"
import "encoding/json"
import "strings"
type JSONableSlice []uint8
func (u JSONableSlice) MarshalJSON() ([]byte, error) {
var result string
if u == nil {
result = "null"
} else {
result = strings.Join(strings.Fields(fmt.Sprintf("%d", u)), ",")
}
return []byte(result), nil
}
type Test struct {
Name string
Array JSONableSlice
}
func main() {
t := &Test{"Go", []uint8{'h', 'e', 'l', 'l', 'o'}}
m, err := json.Marshal(t)
if err != nil {
fmt.Println(err)
}
fmt.Printf("%s", m) // {"Name":"Go","Array":[104,101,108,108,111]}
}
http://play.golang.org/p/6aURXw8P5d
这篇关于如何在 Go 中将 byte/uint8 数组编组为 json 数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!