首页 > 解决方案 > 将 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

标签: go

解决方案


推荐阅读