How to Preserve Original String Content When Marshaling a `[]byte` Field in a Go Struct as JSON?

Mary-Kate Olsen
Release: 2024-11-06 11:04:02
Original
202 people have browsed it

How to Preserve Original String Content When Marshaling a `[]byte` Field in a Go Struct as JSON?

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))
}
Copy after login

Produces the JSON string:

{"Content":"SGVsbG8="}
Copy after login

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))
}
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!