go - 将 map[string]interface{} 转换为 JSON,将相同的 JSON 转换为 map[string]interface{}(保留 interface{} 类型)
问题描述
我将结构名称和类型放入映射中,将此映射编组为 JSON 并将此 JSON 解组回映射,我可以像以前一样提取每个结构的类型。
这是尝试过的: 1 - 有预定义的结构 2 - 定义一个 map[string]interface{} 3 - 使用结构名称作为键和结构类型作为 interface() 值填充此映射。4 - 将此地图编组为 JSON。5 - 定义一个新的 map[string]interface{} 6 - 将 JSON 解组到这个新映射中,以供以后在程序中使用。我希望保持 interface{} 的反射类型相同。
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 \n", 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 \n", k, v)
fmt.Printf("myMap: reflect.TypeOf(v) is: %v \n", 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 \n", k, v)
fmt.Printf("newMap: reflect.TypeOf(v) is: %v \n", reflect.TypeOf(v).Kind())
fmt.Println()
}
两个地图的 reflect.TypeOf(v).Kind() 应该是结构。但事实并非如此。对于 myMap,Kind 是 struct(这是正确的),但对于 newMap,Kind 是不正确的 map。我在这里想念什么。以下是 play.golang.org 上的完整代码:https: //play.golang.org/p/q8BBLlw3fMA
解决方案
推荐阅读
- html - 将一个 div 放在另一个 div 下方并防止重叠
- javascript - 如何在 React 中从可重用表单中传递道具
- python-3.x - 无法启动 lighttpd 服务守护进程
- spring - 如何在 BeanFactoryPostProcessor 中获取命令行参数?
- unit-testing - 如何在某些测试中隐藏日志但在其他测试中不隐藏?
- selenium - 如何处理硒中的铬通知?
- sql-server-2008 - 递归 CTE 以提取 BOM(物料清单)
- high-availability - 如何在 HA 模式下使用首选主机配置 Wildfly 11?
- c# - 温莎城堡是否有一个命名约定来自动判断生活方式?
- python - 使用 ElementTree 仅复制带有相关帖子的 XML 结构