简体   繁体   中英

JSON marshalling with type not exported

I'm want to use a custom type which is not exported and define an interface to use it. The custom type will implement the interface and everything works fine except for unmarshaling from JSON.

I created an example to explain it better:

type (
    Value interface {
        Set(k, v string)
    }

    value map[string]string
)

func New() Value {
    return value{}
}

func (val value) Set(k, v string) {
    val[k] = v
}

This approach will not provide direct access to the map and force the usage of New() function to create objects of type "Value".

When trying to unmarshal in an object created with New() I'm getting the error:

Failed to unmarshal value json: cannot unmarshal object into Go value of type main.Value

That can be fixed by making New() return "value" instead of "Value" but will still be a problem when trying to unmarshal an object like:

Storage struct {
        Val Value `json:"val"`
}

Any suggestions? Implementing Unmarshaler doesn't help in this case. I create a go snippet with this example: https://play.golang.org/p/IEalgBCsTVR

You need to give json.Unmarshal() a pointer to a concrete type. So change (from your linked playground):

unm := New()

to

unm := New().(value)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM