By default byte slices are marshalled as Base64 strings and byte arrays are converted as is:
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)
}
Output:
{"ByteSlice":"AAAAAQID","ByteArray":[0,0,0,1,2,3]}
Is there a way to use hex string conversion for byte slices?
Is there a way to use hex string conversion for byte slices?
No there is not.
You have to encode it yourself. Either into a new struct with a string field or by writing your own UnmarshalJSON method as described in package json's doc.
You could customize JSON serialization if you define a custom type. I've substitute []byte
for instance:
Output:
{"ByteSlice":"000000010203","ByteArray":[0,0,0,1,2,3]}
Code:
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
", text)
}