Home > Backend Development > Golang > How to Idiomatically Embed a Struct with a Custom `MarshalJSON()` in Go?

How to Idiomatically Embed a Struct with a Custom `MarshalJSON()` in Go?

Patricia Arquette
Release: 2024-12-06 13:18:11
Original
325 people have browsed it

How to Idiomatically Embed a Struct with a Custom `MarshalJSON()` in Go?

Idiomatic Method for Embedding a Struct with a Custom MarshalJSON()

The challenge arises when an embedded struct defines a customized MarshalJSON() method, causing unexpected JSON serialization behavior when attempting to marshal the containing struct.

Background

Consider the following struct definitions:

1

2

3

4

5

6

7

8

type Person struct {

    Name string `json:"name"`

}

 

type Employee struct {

    *Person

    JobRole string `json:"jobRole"`

}

Copy after login

Marshaling the Employee struct as expected is straightforward:

1

2

3

4

p := Person{"Bob"}

e := Employee{&p, "Sales"}

output, _ := json.Marshal(e)

fmt.Printf("%s\n", string(output))

Copy after login

Output:

1

{"name":"Bob","jobRole":"Sales"}

Copy after login

The Problem

However, defining a custom MarshalJSON() method for the embedded struct, as shown below, disrupts the intended serialization:

1

2

3

4

5

6

7

func (p *Person) MarshalJSON() ([]byte, error) {

    return json.Marshal(struct{

        Name string `json:"name"`

    }{

        Name: strings.ToUpper(p.Name),

    })

}

Copy after login

Now, marshaling the Employee produces output with the name field converted to uppercase but misses the jobRole field:

1

{"name":"BOB"}

Copy after login

Idiomatic Solution

To maintain the desired serialization behavior, avoid defining a MarshalJSON() method on the embedded struct (Person). Instead, create a separate type encapsulating the custom marshalling logic and embed that type:

1

2

3

4

5

6

7

8

9

10

11

12

13

type Name string

 

func (n Name) MarshalJSON() ([]byte, error) {

    return json.Marshal(struct{

        Name string `json:"name"`

    }{

        Name: strings.ToUpper(string(n)),

    })

}

 

type Person struct {

    Name Name `json:"name"`

}

Copy after login

This approach isolates the marshalling customization to a dedicated type, preventing unexpected side effects when embedding the Person struct elsewhere.

Example: https://play.golang.org/p/u96T4C6PaY

The above is the detailed content of How to Idiomatically Embed a Struct with a Custom `MarshalJSON()` in Go?. 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