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

Unmarshal into struct with field of type func differs from encoding/json #255

Closed
Kiraub opened this issue Jun 23, 2021 · 2 comments
Closed

Comments

@Kiraub
Copy link
Contributor

Kiraub commented Jun 23, 2021

Versions:
go version go1.16.5 windows/amd64
github.com/goccy/go-json v0.7.1

What did I try to do:

Use Unmarshal to decode a JSON string into a struct that has a field of type func.

What did I expect:

Analog to encoding/json the field of type func receives the null value (nil) if the field is not found in the JSON object.

If the field is found and has value other than null return with an error in the format:

json: cannot unmarshal <found type> into Go struct field <struct type>.<field name> of type <func type>

If the field is found and has value null it receives the null value.

What happened instead:

Unmarshal returns an error in the format:

json: cannot unmarshal object into Go value of type <func type>

where object does not necessarily represent the type of the actual found/ not found value.

Example:

package goccyjson_test

import (
	json_ "encoding/json"
	"testing"

	"github.com/goccy/go-json"
)

type withFunc struct {
	Name     string
	SomeFunc func() string
}

var text = []byte(`{"Name": "HelloWorld"}`)

func TestWithFuncUnmarshal(t *testing.T) {
	var e, e_ withFunc
	err := json.Unmarshal(text, &e)
	if err != nil {
		t.Log(err)
	} else {
		t.Logf("%#v", e)
	}
	err_ := json_.Unmarshal(text, &e_)
	if err_ != nil {
		t.Log(err_)
	} else {
		t.Logf("%#v", e_)
	}
	if err != nil && err_ == nil {
		t.Fail()
	} 
}
@Kiraub
Copy link
Contributor Author

Kiraub commented Jun 23, 2021

The error is generated inside internal/decoder/compile.go#compile since the switch statement does not handle fields of type reflect.Func

@Kiraub
Copy link
Contributor Author

Kiraub commented Jun 24, 2021

Fixed with #257

@Kiraub Kiraub closed this as completed Jun 24, 2021
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