Skip to content

Instantly share code, notes, and snippets.

@nikravi
Last active April 16, 2018 02:10
Show Gist options
  • Save nikravi/e4812ed46ad77d8d2aee60faddd205df to your computer and use it in GitHub Desktop.
Save nikravi/e4812ed46ad77d8d2aee60faddd205df to your computer and use it in GitHub Desktop.
Golang bytearray hex json representation, Playground: https://play.golang.org/p/fO7lmZ5WjWq
package main
import (
"encoding/hex"
"encoding/json"
"fmt"
"os"
)
// JSN has some struct for json
type JSN struct {
Bytes ByteString `json:"bytes"`
Name string `json:"name"`
}
// ByteString is a byte array that serializes to hex
type ByteString []byte
// MarshalJSON serializes ByteArray to hex
func (s ByteString) MarshalJSON() ([]byte, error) {
bytes, err := json.Marshal(fmt.Sprintf("%x", string(s)))
return bytes, err
}
// UnmarshalJSON deserializes ByteArray to hex
func (s *ByteString) UnmarshalJSON(data []byte) error {
var x string
err := json.Unmarshal(data, &x)
if err == nil {
str, e := hex.DecodeString(x)
*s = ByteString([]byte(str))
err = e
}
return err
}
func main() {
j := JSN{[]byte("test"), "Michael"}
marshaledJ := toJSON(j)
fmt.Printf("json is %s\n\n", marshaledJ)
unmarshaledJ := JSN{}
json.Unmarshal([]byte(marshaledJ), &unmarshaledJ)
fmt.Printf("Deserialized: bArray: %s name: %s\n",
string(unmarshaledJ.Bytes), unmarshaledJ.Name)
}
func toJSON(p interface{}) string {
bytes, err := json.Marshal(p)
if err != nil {
fmt.Println(err.Error())
os.Exit(1)
}
return string(bytes)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment