Sarat Chandra
Sarat Chandra

Reputation: 51

Unmarshalling array of bytes to an interface and type cast that interface into struct doesn't work?

I have been coding in golang for a while now. I have come across something I thought would work perfectly fine.

When I JSON Marshal a nested struct in golang I get the array of bytes, when I UnMarshal the same into an interface and convert the interface into the respective nested struct, it gives me a panic stating interface conversion: interface is map[string]interface but not the nested struct.

Please go through the link below.

https://play.golang.org/p/apdR4TKjee-

Can someone explain to me what is that I am missing?

Upvotes: 3

Views: 11123

Answers (2)

Adrian
Adrian

Reputation: 2113

You can not unmarshal to nil interface, however, if interface has a pointer to undelying structure it will work see below your updated code:


    package main

    import (
        "encoding/json"
        "fmt"
        "github.com/viant/toolbox"
        "log"
    )

    type sample struct {
        Ping string  `json:"ping"`
        Pong sample1 `json:"long"`
    }
    type sample1 struct {
        Play string `json:"plong"`
    }

    func main() {

        var ans sample
        var result interface{} = &sample{}
        ans.Ping = "asda"
        var ans1 sample1
        ans1.Play = "asasd"
        ans.Pong = ans1
        fmt.Println(ans)



        converter := toolbox.NewColumnConverter(toolbox.DefaultDateLayout)
        var aMap = make(map[string]interface{})
        converter.AssignConverted(&aMap, ans)



        data, err := json.Marshal(ans)
        fmt.Println(err)
        fmt.Println(string(data), err)



        err = json.Unmarshal(data,&result)
        fmt.Println(result)
        if err!= nil{
            log.Fatal(err)
        }

        fmt.Println(result.(*sample))
        fmt.Println(result)

    }


Upvotes: 0

Adrian
Adrian

Reputation: 46432

When you unmarshall JSON into interface{}, it has no way to know what type you want it to use, so it defaults to map[string]interface{} as indicated in the documentation:

To unmarshal JSON into an interface value, Unmarshal stores one of these in the interface value:

...

map[string]interface{}, for JSON objects

If you want to unmarshal to a specific type, pass an instance of that type to Unmarshal:

var result sample 
err = json.Unmarshal(data,&result)

Upvotes: 5

Related Questions