Skip to content

proposal: encoding/json support Unmarshal type interfaceΒ #23549

@diiyw

Description

@diiyw
package main

import (
	"fmt"
	"encoding/json"
)

type Interface interface {
	Inter()
}

type A struct {
	AValue string
}

func(a *A)Inter() {}

type B struct {
	BValue string
}

func(b *B)Inter() {}


func main() {
	var i Interface
	err := json.Unmarshal([]byte("{\"BValue\":\"B\"}"), &i)
	if err != nil {
		fmt.Println(err)
	}
}

error:json: cannot unmarshal object into Go value of type main.Interface.

A and B implemented Unmarshaler :

package main

import (
	"fmt"
	"encoding/json"
)

type Interface interface {
	Inter()
	UnmarshalJSON([]byte) error
}

type A struct {
	AValue string
}

func(a *A)Inter() {}

func(a *A)UnmarshalJSON([]byte) error{
	return nil
}

type B struct {
	BValue string
}

func(b *B)Inter() {}
func(b *B)UnmarshalJSON([]byte) error{
	return nil
}


func main() {
	var i Interface
	err := json.Unmarshal([]byte("{\"BValue\":\"B\"}"), &i)
	if err != nil {
		fmt.Println(err)
	}
}

The same error,also not ok.
But Marshaler could marshaled.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions