What’s the proper way to convert a json.RawMessage to a struct?

As said, the underlying type of json.RawMessage is []byte, so you can use a json.RawMessage as the data parameter to json.Unmarshal.

However, your problem is that you have a pointer (*json.RawMessage) and not a value. All you have to do is to dereference it:

err := json.Unmarshal(*out.Hits.Hits[0].Source, &mySyncInfo)

Working example:

package main

import (
    "encoding/json"
    "fmt"
)

type SyncInfo struct {
    Target string
}

func main() {
    data := []byte(`{"target": "localhost"}`)
    Source := (*json.RawMessage)(&data)

    var mySyncInfo SyncInfo
    // Notice the dereferencing asterisk *
    err := json.Unmarshal(*Source, &mySyncInfo)
    if err != nil {
        panic(err)
    }

    fmt.Printf("%+v\n", mySyncInfo)
}

Output:

{Target:localhost}

Playground: http://play.golang.org/p/J8R3Qrjrzx

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)