封送到 json 时如何强制 go 将"[8]字节"编码为十六进制



默认情况下,字节片被封送为 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)
}

输出:

{"ByteSlice":"AAAAAQID","ByteArray":[0,0,0,1,2,3]}

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

如果定义自定义类型,则可以自定义 JSON 序列化。例如,我替换了[]byte

输出:

{"ByteSlice":"000000010203","ByteArray":[0,0,0,1,2,3]}

法典:

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("%sn", text)
}

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

不,没有。

您必须自己对其进行编码。要么使用字符串字段进入新结构,要么编写自己的 UnmarshalJSON 方法,如包 json 的文档中所述。

没有简单的方法来更改golang默认字节编码器。

  1. 使用结构体 Foo 自定义封送和解封,这种方式可以适合大多数情况,但是当我们有像"类型 Hash [32]byte"这样的基本类型时,并在不同的结构中使用它。 然后我们必须为所有结构编写元帅和取消封送。

  2. 像上面的答案一样,为 cutom 封送定义一个新类型,但 func 必须使用指针而不是值类型:

type Hash []byte
func (h *Hash) MarshalJSON() ([]byte, error) {
...
}
func (h *Hash) UnmarshalJSON(b []byte) error {
...
}

并更改结构定义:

type Foo struct {
ByteSlice *Hash
ByteArray [6]byte
}

必须使用指针定义,否则不会使用自定义封送和取消封送

最新更新