Created
April 15, 2020 18:58
-
-
Save emmiep/bbdef061cd5a9cdfd6c97268f16c8cca to your computer and use it in GitHub Desktop.
Hex byte array JSON encoding
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"encoding/hex" | |
"encoding/json" | |
"fmt" | |
) | |
type HexEncodedByteArray []byte | |
type Message struct { | |
Text string | |
ID HexEncodedByteArray | |
} | |
func (b HexEncodedByteArray) MarshalJSON() ([]byte, error) { | |
hexString := hex.EncodeToString(b) | |
return json.Marshal(hexString) | |
} | |
func (b *HexEncodedByteArray) UnmarshalJSON(data []byte) (err error) { | |
var hexString string | |
if err = json.Unmarshal(data, &hexString); err != nil { | |
return | |
} | |
*b, err = hex.DecodeString(hexString) | |
return | |
} | |
func testMarshal() { | |
var ( | |
data []byte | |
err error | |
) | |
message := Message{ | |
Text: "Marshal this message", | |
ID: HexEncodedByteArray{0x86, 0xCE, 0xC5, 0x88, 0x22, 0x4B, 0x04, 0x7F}, | |
} | |
if data, err = json.Marshal(message); err != nil { | |
panic(err) | |
} | |
fmt.Println("Marshaled message:", string(data)) | |
} | |
func testUnmarshal() { | |
data := `{ | |
"Text": "Unmarshal this message", | |
"ID": "86CEC588224B047F" | |
}` | |
message := &Message{} | |
if err := json.Unmarshal([]byte(data), message); err != nil { | |
panic(err) | |
} | |
fmt.Println("Unmarshaled message:", message) | |
} | |
func main() { | |
testMarshal() | |
testUnmarshal() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment