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

Interface decoder is not compatible with standard library #443

Open
arekziobrowski opened this issue Mar 20, 2023 · 0 comments
Open

Interface decoder is not compatible with standard library #443

arekziobrowski opened this issue Mar 20, 2023 · 0 comments

Comments

@arekziobrowski
Copy link

When trying to unmarshal into the interface, the interface decoder is expecting the UnmarshalJSON method to be defined on the underlying struct [source]. Otherwise, it checks if the value is null and ultimately fails if neither condition applies with:

json: cannot unmarshal X into Go value of type X

The standard library behaviour though is handling such situations and does not fail.

I'm using Go version 1.19.

Code to reproduce this issue

package main

import (
	"github.com/goccy/go-json"
	"log"
	"time"
)

type ExampleInterface interface {
	Method(a string) error
}

type ExampleStruct struct {
	Value     string    `json:"value"`
	CreatedAt time.Time `json:"createdAt"`
}

func (e *ExampleStruct) Method(a string) error {
	return nil
}

var bb = []byte(`{"value":"abc","createdAt":"2023-03-20T08:15:07.526300877Z"}`)

func main() {
	unmarshalled, err := unmarshal(&ExampleStruct{})
	if err != nil {
		log.Fatal(err)
	}
	log.Println(unmarshalled)
}

// This fails.
func unmarshal(a ExampleInterface) (ExampleInterface, error) {
	data := bb
	if err := json.Unmarshal(data, &a); err != nil {
		return a, err
	}
	return a, nil
}

// This works.
func unmarshalStruct(a *ExampleStruct) (*ExampleStruct, error) {
	data := bb
	if err := json.Unmarshal(data, &a); err != nil {
		return a, err
	}
	return a, nil
}

Output of the main function run is:

json: cannot unmarshal main.ExampleInterface into Go value of type main.ExampleInterface

I can contribute some example test cases if this would be helpful!

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