Marshaling JSON []byte as Strings
Question:
In Go, when encoding a struct containing a []byte field as JSON, the resulting JSON includes a non-expected string representation of the slice contents. For example, the code:
type Msg struct { Content []byte } func main() { helloStr := "Hello" helloSlc := []byte(helloStr) json, _ := json.Marshal(Msg{helloSlc}) fmt.Println(string(json)) }
Produces the JSON string:
{"Content":"SGVsbG8="}
What conversion is performed by json.Marshal on the slice contents, and how can the original string content be preserved?
Answer:
Base64 Encoding
By default, Go's json.Marshal function encodes []byte arrays as base64-encoded strings to represent raw bytes in JSON. According to the JSON specification, JSON doesn't have a native representation for raw bytes.
Custom Marshaling:
To preserve the original string content, custom marshaling can be implemented by defining a custom MarshalJSON method for the Msg struct:
import ( "encoding/json" "fmt" ) type Msg struct { Content []byte } func (m Msg) MarshalJSON() ([]byte, error) { return []byte(fmt.Sprintf(`{"Content": "%s"}`, m.Content)), nil } func main() { helloStr := "Hello" helloSlc := []byte(helloStr) json, _ := json.Marshal(Msg{helloSlc}) fmt.Println(string(json)) }
This custom implementation encodes the Content field as a string within the JSON object, preserving its original content.
The above is the detailed content of How to Preserve Original String Content When Marshaling a `[]byte` Field in a Go Struct as JSON?. For more information, please follow other related articles on the PHP Chinese website!