去:marshal []字节到JSON,给出一个奇怪的字符串 [英] Go: marshal []byte to JSON, giving a strange string

查看:108
本文介绍了去:marshal []字节到JSON,给出一个奇怪的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



请看下面的代码。



我有两个疑问:

我怎样才能将[] byte传给JSON?

为什么[]字节变成这个字符串?

  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, 单字节:10 IntSlice:[0,0,0,1,2, 3]} 

golang操场: https://play.golang.org/p/wanppBGzNR

解决方案

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


数组和切片值编码为JSON数组,除了[]字节编码为base64编码的字符串,并且

AAAAAQID 是一个零片段,它编码为空的JSON对象。一个base64表示你的字节片 - 例如

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

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


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

Please look the following code.

I have two doubt:

How can I marshal []byte to JSON?

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)
}

the output is:

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

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

解决方案

As per the docs: https://golang.org/pkg/encoding/json/#Marshal

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.

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]

这篇关于去:marshal []字节到JSON,给出一个奇怪的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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