我有一个带[] uint8成员的结构,我用json.Marshal编写它.麻烦的是,它将uint8s解释为chars,它输出的是字符串而不是数字数组.
如果它是[] int,我可以让它工作,但如果我可以避免它,我不想分配和复制项目.我可以吗?
根据
docs,[]字节将被编码为Base64字符串.
“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.”
所以我认为您可能需要通过实现自己的MarshalJSON方法来使您的结构实现Marshaler接口,该方法在您的[] uint8中生成更理想的JSON数组编码.
举个例子:
- 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','o'}}
- m,err := json.Marshal(t)
- if err != nil {
- fmt.Println(err)
- }
- fmt.Printf("%s",m) // {"Name":"Go","Array":[104,101,108,111]}
- }
http://play.golang.org/p/Tip59Z9gqs
或者更好的想法是创建一个以[] uint8作为其基础类型的新类型,使该类型成为Marshaler,并在结构中使用该类型.
- 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",111]}
- }