FAQ
Hello fellow Gophers.

You may have noticed that json.Unmarshal always refuses to deserialise JSON
into a custom interface type. For example, if you have a custom interface:

type Fruit interface {
Name() string
}

...And you wish you deserialise a Lemon:

type Lemon struct {
KindOfLemon string
}
func (le Lemon) Name() string {
return le.KindOfLemon
}

...But your code cannot touch Lemon directly, all you have is a Fruit:

var deserialisedLime Fruit = Lemon{}
fmt.Println(json.Unmarshal(serialsedLime, &deserialisedLime))

Unmarshal function will complain that it "cannot unmarshal object into Go
value of type <interface name>".

However, the statement is not entirely true, json package is perfectly
capable of doing that, although the workaround involves
reflection: https://play.golang.org/p/-VYz3LxYmp

Enjoy!

Kind regards,
Howard

--
You received this message because you are subscribed to the Google Groups "golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts+unsubscribe@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Search Discussions

Discussion Posts

Follow ups

Related Discussions

Discussion Navigation
viewthread | post
posts ‹ prev | 1 of 2 | next ›
Discussion Overview
groupgolang-nuts @
categoriesgo
postedMay 3, '16 at 2:24p
activeMay 3, '16 at 10:35p
posts2
users2
websitegolang.org

2 users in discussion

Howard Guo: 1 post Lars Seipel: 1 post

People

Translate

site design / logo © 2021 Grokbase