Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

encoding/json: Marshal on []byte is not working #24397

Closed
inkeliz opened this issue Mar 14, 2018 · 2 comments
Closed

encoding/json: Marshal on []byte is not working #24397

inkeliz opened this issue Mar 14, 2018 · 2 comments

Comments

@inkeliz
Copy link

inkeliz commented Mar 14, 2018

Please answer these questions before submitting your issue. Thanks!

What version of Go are you using (go version)?

go version go1.10 windows/amd64

Does this issue reproduce with the latest release?

Yes

What operating system and processor architecture are you using (go env)?

set GOARCH=amd64
set GOBIN=
set GOEXE=.exe
set GOHOSTARCH=amd64
set GOHOSTOS=windows
set GOOS=windows

What did you do?

Creating one type that is alias to []byte will not trigger the Marshal, but triggers the Unmarshal, like:

type MyType []byte

type StructJSON struct {
	Name MyType
}

func (d *MyType) MarshalJSON() ([]byte, error) {   // << Never will be triggered
}

func (d *MyType) UnmarshalJSON(data []byte) (err error) { // << Working :)
}

See the demonstration at https://play.golang.org/p/FHOMVOq1oDD

What did you expect to see?

I expect that the same result of UnmarshalJSON. In the demonstration the message of Marshal is working should be displayed.

What did you see instead?

The MarshalJSON() are not beginning triggered and don't have the same behavior of UnmarshalJSON.

@inkeliz inkeliz closed this as completed Mar 14, 2018
@inkeliz
Copy link
Author

inkeliz commented Mar 14, 2018

Replacing *MyType to MyType will work.

@andybons
Copy link
Member

In your playground example, replace result, _ := json.Marshal(st) with result, _ := json.Marshal(&st)

The Marshal method is defined on a pointer receiver. If you defined it as

func (d MyType) MarshalJSON() ([]byte, error) {
  ...
}

Then result, _ := json.Marshal(st) would work, like you said.

@golang golang locked and limited conversation to collaborators Mar 14, 2019
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Projects
None yet
Development

No branches or pull requests

3 participants