将[] byte封送为JSON,并提供了一个奇怪的字符串 [英] Marshal []byte to JSON, giving a strange string

查看:115
本文介绍了将[] byte封送为JSON,并提供了一个奇怪的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我尝试将[] bytes封送为JSON格式时,我只有一个奇怪的字符串.

When I try to marshal []byte to JSON format, I only got a strange string.

请查看以下代码.

我有两个疑问:

如何将[] bytes封送至JSON?

How can I marshal []byte to JSON?

为什么[] byte成为此字符串?

Why []byte become this string?

package main

import (
    "encoding/json"
    "fmt"
    "os"
)

func main() {
    type ColorGroup struct {
        ByteSlice    []byte
        SingleByte   byte
        IntSlice     []int
    }
    group := ColorGroup{
        ByteSlice:  []byte{0,0,0,1,2,3},
        SingleByte: 10,
        IntSlice:   []int{0,0,0,1,2,3},
    }
    b, err := json.Marshal(group)
    if err != nil {
        fmt.Println("error:", err)
    }
    os.Stdout.Write(b)
}

输出为:

{"ByteSlice":"AAAAAQID","SingleByte":10,"IntSlice":[0,0,0,1,2,3]}

golang游乐场: https://play.golang.org/p/wanppBGzNR

golang playground: https://play.golang.org/p/wanppBGzNR

推荐答案

根据文档: https://golang.org/pkg/encoding/json/#Marshal

数组和切片值编码为JSON数组,除了[] byte编码为base64编码的字符串,而nil slice编码为空JSON对象.

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.

AAAAAQID是您的字节片的base64表示形式-例如

The value AAAAAQID is a base64 representation of your byte slice - e.g.

b, err := base64.StdEncoding.DecodeString("AAAAAQID")
if err != nil {
    log.Fatal(err)
}

fmt.Printf("%v", b)
// Outputs: [0 0 0 1 2 3]

这篇关于将[] byte封送为JSON,并提供了一个奇怪的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆