我想将各种对象编组到文件中,然后解组它们,并通过获取编组的变量的类型将它们转换回原始类型。关键是我想将未编组的对象转换为指定变量的类型,而不指定类型。
简短的伪代码:
// Marshal this
item := Book{"The Myth of Sisyphus", "Albert Camus"}
// Then unmarshal and convert to the type of the item variable.
itemType := reflect.TypeOf(item)
newItem itemType = unmarshalledItem.(itemType) // This is the problem.
fmt.Println("Unmarshalled is:", reflect.TypeOf(newItem)) // Should print *main.Book
完整代码:
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"os"
"reflect"
)
type Book struct {
Title string
Author string
}
func main() {
// Create objects to marshal.
book := Book{"The Myth of Sisyphus", "Albert Camus"}
box := make(map[string]interface{})
box["The Myth of Sisyphus"] = &book
itemType := reflect.TypeOf(box["The Myth of Sisyphus"])
fmt.Println("Book is:", itemType)
// Marshal objects to file.
err := Write(&book)
if err != nil {
fmt.Println("Unable to save store.", err)
return
}
// Unmarshal objects from file.
untyped := make(map[string]interface{})
bytes, err := ioutil.ReadFile("store.txt")
if err != nil {
fmt.Println("Unable to load store.", err)
return
}
err = json.Unmarshal(bytes, &untyped)
if err != nil {
fmt.Println("Err in store unmarshal.", err)
return
}
// Get Title property of unmarshalled object,
// and use that to get variable type from box map.
for k, v := range untyped {
if k == "Title" {
itemTitle := v.(string)
fmt.Println("Cast item having title:", itemTitle)
targetType := reflect.TypeOf(box[itemTitle])
fmt.Println("Type to cast to is:", targetType)
// Convert untyped to targetType.
// This is the problem.
typed targetType = untyped.(targetType)
fmt.Println("Unmarshalled is:", reflect.TypeOf(typed)) // Should print *main.Book
}
}
}
相关分类