编组到 json 时如何强制 go 将 `[8]byte` 编码为十六进制

Pom*_*oma 6 json go

默认情况下,字节切片被编组为 Base64 字符串,字节数组按原样转换:

func main() {
    type Foo struct {
        ByteSlice []byte
        ByteArray [6]byte
    }

    foo := Foo {
        ByteSlice: []byte{0, 0, 0, 1, 2, 3},
        ByteArray: [6]byte{0, 0, 0, 1, 2, 3},
    }
    text, _ := json.Marshal(foo)
    fmt.Printf("%s", text)
}
Run Code Online (Sandbox Code Playgroud)

输出:

{"ByteSlice":"AAAAAQID","ByteArray":[0,0,0,1,2,3]}
Run Code Online (Sandbox Code Playgroud)

有没有办法对字节切片使用十六进制字符串转换?

Arm*_*ani 5

如果您定义自定义类型,则可以自定义 JSON 序列化。我已经替换[]byte为例如:

输出:

{"ByteSlice":"000000010203","ByteArray":[0,0,0,1,2,3]}
Run Code Online (Sandbox Code Playgroud)

代码:

package main

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

type MyByteSlice []byte

func (m MyByteSlice) MarshalJSON() ([]byte, error) {
    return json.Marshal(hex.EncodeToString(m))
}

func main() {
    type Foo struct {
        ByteSlice MyByteSlice
        ByteArray [6]byte
    }

    foo := Foo {
        ByteSlice: []byte{0, 0, 0, 1, 2, 3},
        ByteArray: [6]byte{0, 0, 0, 1, 2, 3},
    }

    text, _ := json.Marshal(foo)
    fmt.Printf("%s\n", text)
}
Run Code Online (Sandbox Code Playgroud)


Vol*_*ker 0

有没有办法对字节切片使用十六进制字符串转换?

不,那里没有。

你必须自己编码。要么写入带有字符串字段的新结构,要么编写自己的 UnmarshalJSON 方法,如 package json 的文档中所述。