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

TIL blog post on pointers, null and UnmarshalJSON() in Go #95

Open
dhermes opened this issue Aug 30, 2022 · 0 comments
Open

TIL blog post on pointers, null and UnmarshalJSON() in Go #95

dhermes opened this issue Aug 30, 2022 · 0 comments

Comments

@dhermes
Copy link
Owner

dhermes commented Aug 30, 2022

If null is the JSON value being deserialized onto a Go pointer, then encoding/json will just skip over the type's custom UnmarshalJSON() altogether. "Obviously null in JSON means nil pointer."

https://go.dev/play/p/adfSt9EbqCp


package main

import (
	"encoding/json"
	"fmt"
	"os"
)

type T struct {
	RawJSON []byte
}

func (t *T) UnmarshalJSON(data []byte) error {
	t.RawJSON = data
	return nil
}

func (t T) MarshalJSON() ([]byte, error) {
	return t.RawJSON, nil
}

type S struct {
	Value   T  `json:"value"`
	Pointer *T `json:"pointer"`
}

func run() error {
	inputs := []string{
		`{}`,
		`{"value": 123}`,
		`{"pointer": 123}`,
		`{"value": null}`,
		`{"pointer": null}`,
		`{"value": null, "pointer": null}`,
		`{"value": 123, "pointer": null}`,
		`{"value": null, "pointer": 123}`,
	}

	for _, input := range inputs {
		s := S{}
		err := json.Unmarshal([]byte(input), &s)
		if err != nil {
			return err
		}

		fmt.Printf("--------------------\ninput:\n  %s\ns:\n  %#v\n", input, s)
	}

	return nil
}

func main() {
	err := run()
	if err != nil {
		fmt.Fprintf(os.Stderr, "%v\n", err)
		os.Exit(1)
	}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant