如何在Go中编组一个byte / uint8数组作为json数组?

前端之家收集整理的这篇文章主要介绍了如何在Go中编组一个byte / uint8数组作为json数组?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一个带[] 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数组编码.

举个例子:

  1. import "fmt"
  2. import "encoding/json"
  3. import "strings"
  4.  
  5. type Test struct {
  6. Name string
  7. Array []uint8
  8. }
  9.  
  10. func (t *Test) MarshalJSON() ([]byte,error) {
  11. var array string
  12. if t.Array == nil {
  13. array = "null"
  14. } else {
  15. array = strings.Join(strings.Fields(fmt.Sprintf("%d",t.Array)),",")
  16. }
  17. jsonResult := fmt.Sprintf(`{"Name":%q,"Array":%s}`,t.Name,array)
  18. return []byte(jsonResult),nil
  19. }
  20.  
  21. func main() {
  22. t := &Test{"Go",[]uint8{'h','e','l','o'}}
  23.  
  24. m,err := json.Marshal(t)
  25. if err != nil {
  26. fmt.Println(err)
  27. }
  28. fmt.Printf("%s",m) // {"Name":"Go","Array":[104,101,108,111]}
  29. }

http://play.golang.org/p/Tip59Z9gqs

或者更好的想法是创建一个以[] uint8作为其基础类型的新类型,使该类型成为Marshaler,并在结构中使用该类型.

  1. import "fmt"
  2. import "encoding/json"
  3. import "strings"
  4.  
  5. type JSONableSlice []uint8
  6.  
  7. func (u JSONableSlice) MarshalJSON() ([]byte,error) {
  8. var result string
  9. if u == nil {
  10. result = "null"
  11. } else {
  12. result = strings.Join(strings.Fields(fmt.Sprintf("%d",u)),")
  13. }
  14. return []byte(result),nil
  15. }
  16.  
  17. type Test struct {
  18. Name string
  19. Array JSONableSlice
  20. }
  21.  
  22. func main() {
  23. t := &Test{"Go",111]}
  24. }

http://play.golang.org/p/6aURXw8P5d

猜你在找的Windows相关文章