-
-
Save jpukg/ca73c350cc0fd78f670b50cfdc893ee6 to your computer and use it in GitHub Desktop.
map -> json -> struct
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"encoding/json" | |
"fmt" | |
) | |
type example struct { | |
Name string | |
Address string | |
Hobbies []string | |
} | |
func main() { | |
m := make(map[string]interface{}) | |
m["name"] = "go" | |
m["address"] = "japan" | |
m["hobbies"] = []string{"watching tv", "listen music"} | |
fmt.Println(m) | |
var ex example | |
MapToStruct(m, &ex) | |
fmt.Println(ex) | |
} | |
func MapToStruct(m map[string]interface{}, val interface{}) error { | |
tmp, err := json.Marshal(m) | |
if err != nil { | |
return err | |
} | |
err = json.Unmarshal(tmp, val) | |
if err != nil { | |
return err | |
} | |
return nil | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment