0

我从其他地方读取配置,它返回一个映射并且所有值都是字符串,并且不确定 Config.Mp 映射中的哪个键,所以我想这样做,但是在 Unmarshal 之后 Mp 为零,我怎么能用好方法吗?钩子什么的?谢谢~

type DB struct {
    Name string   `mapstructure:"name"`
    Ip   string   `mapstructure:"ip"`
    Vars []string `mapstructure:"vars"`
}

type Config struct {
    Aid      string                 `mapstructure:"aid"`
    Times    int                    `mapstructure:"times"`
    Mp       map[string]interface{} `mapstructure:"mp"`
    DBConfig DB                     `mapstructure:"db"`
}

func map2Struct() {

    m := make(map[string]interface{})

    m["aid"] = "123"
    m["db.name"] = "test"
    m["db.ip"] = "10.0.0.2"
    m["db.vars"] = `a, b`
    m["times"] = "1"
    m["mp"] = `{"a": 1, "b": 0.1, "c": "asd", d:[1,2]}`
    v := viper.New()
    v.MergeConfigMap(m)
    v.SetConfigType("properties")

    config := Config{}
    v.Unmarshal(&config)
}

4

1 回答 1

0

建议但不是必须在使用嵌入式结构时squash使用.renamemapstructure

我已按如下方式重新生成了您的方案:

type User struct {
    Name string   `mapstructure:"name"`
    Ip   string   `mapstructure:"ip"`
    Vars []string `mapstructure:"vars"`
}

type Config struct {
    Aid   string                 `mapstructure:"aid"`
    Times int                    `mapstructure:"times"`
    Mp    map[string]interface{} `mapstructure:"mp"`
    User  `mapstructure:",squash"`
}

func main() {

    input := map[string]interface{}{

        "name":  "test",
        "ip":    "10.0.0.2",
        "vars":  []string{"one", "two", "three"},
        "aid":   "123",
        "times": 12,
        "mp": map[string]interface{}{
            "a": 1,
            "b": 0.1,
            "c": "asd",
            "d": []int{1, 2},
        },
    }

    // convert map to json
    jsonString, _ := json.Marshal(input)
    fmt.Println(string(jsonString))

    // convert json to struct
    s := Config{}
    json.Unmarshal(jsonString, &s)
    fmt.Println(s)

}

你可以在这里运行它:https ://go.dev/play/p/dnoskAmJfry

如果您想使用,请viper替换:

 // convert map to json
    jsonString, _ := json.Marshal(input)
    fmt.Println(string(jsonString))

    // convert json to struct
    s := Config{}
    json.Unmarshal(jsonString, &s)
    fmt.Println(s)

有了这个 :

v := viper.New()
v.MergeConfigMap(input)
v.SetConfigType("properties")

config := Config{}
v.Unmarshal(&config)
fmt.Println(config)
于 2021-12-10T09:46:32.893 回答