-1

I am probably doing something wrong when serializing/deserializaing structures w/ JSON. When asserting the interface after JSON deserilization:

AData2 = anInterface.(Data)

At runtime go is expecting a map[string]interface but the object is of type Data:

type Data struct {
    Content string
    Links   []string
}

It throws the error:

panic: interface conversion: interface {} is map[string]interface {}, not main.Data

Full code at https://play.golang.org/p/jm3_ut3R56n

Thanks in advance for any hint.

  • 4
    You should unmarshal directly to the struct, like this `err = json.Unmarshal(value, &AData2)` – Ilya Sep 03 '20 at 10:22
  • 1
    Create a [mcve]. Are you converting the JSON `[]byte` to an interface first, then converting it to a struct? In that case you could unmarshal directly to the struct by adding json properties to the type definition. – super Sep 03 '20 at 10:27
  • 1
    If you need the conversion to map[string]interface{} before converting to a `Data` you can have a look at [this question](https://stackoverflow.com/questions/26744873/converting-map-to-struct). – super Sep 03 '20 at 10:31

1 Answers1

2

You just cannot just assert any interface into random struct type or something like that.

If the that interface was actually that struct type data, only then you can assert that interface to that struct type data.


type Data struct {
    Content string
    Links   []string
}

func main() {
    var AData, AData2 Data
    var anInterface interface{}

    // populate data
    AData.Content = "hello world"
    AData.Links = []string{"link1", "link2", "link3"}
    anInterface = AData
    AData2 = anInterface.(Data)
}

You see anInterface was already a Data type value, that's why we can assert this to Data type again.

Another thing, if you actually want to deserialize your json data into Data type structure, you should directly unmarshal into that variable.

var AData2 Data

err = json.Unmarshal([]byte(value), &AData2)
if err != nil {
    panic(err)
}
Masudur Rahman
  • 1,585
  • 8
  • 16
  • 1
    Do not confuse [type conversion](https://golang.org/ref/spec#Conversions) with [type assertions](https://golang.org/ref/spec#Type_assertions). There is no type conversion in this code. – Peter Sep 03 '20 at 12:20