I am putting structs names and types into a map, Marshal this map into a JSON and Unmarshal this JSON back into a map which I can extract the types of each struct the same as before.
Here is what tried: 1 - have predefined structs 2 - define a map[string]interface{} 3 - populate this map with the struct name as key and struct type as interface() value. 4 - Marshaled this map into a JSON. 5 - Define a new map[string]interface{} 6 - Unmarshal the JSON into this new map for later use in the program. My hope is to preserve the the reflect types of the interface{} the same.
package main
import (
"encoding/json"
"fmt"
"reflect"
)
// Gallery :
type Gallery struct {
ID int
Name string
Images []Image
}
// Image :
type Image struct {
Source string
Height int
Width int
}
func main() {
myMap := make(map[string]interface{})
myMap["Gallery"] = Gallery{}
// encode this map into JSON, jStr:
jStr, err := json.Marshal(&myMap)
if err != nil {
fmt.Println(err)
}
// print the JSON string, just for testing.
fmt.Printf("jStr is: %v
", string(jStr))
// create a newMap and populate it with the JSON jStr
newMap := make(map[string]interface{})
err = json.Unmarshal(jStr, &newMap)
if err != nil {
fmt.Println(err)
}
fmt.Println()
// iterate over myMap and inspect the reflect type of v
for k, v := range myMap {
fmt.Printf("myMap: k is: %v \t v is: %v
", k, v)
fmt.Printf("myMap: reflect.TypeOf(v) is: %v
", reflect.TypeOf(v).Kind())
}
fmt.Println()
// iterate over newMap and inspect the reflect type of v
for k, v := range newMap {
fmt.Printf("newMap: k is: %v \t v is: %v
", k, v)
fmt.Printf("newMap: reflect.TypeOf(v) is: %v
", reflect.TypeOf(v).Kind())
fmt.Println()
}
The reflect.TypeOf(v).Kind() for both maps should be struct. But it is not the case. for myMap, the Kind is struct (which is correct), but for newMap, the Kind is map which is NOT correct. What am I missing here. Here is the full code on play.golang.org: https://play.golang.org/p/q8BBLlw3fMA