map [string] interface {}以使用json标签构造

AbA*_*AbA 1 go

我需要将map[string]interface{}其键为json标记名称的转换为struct

type MyStruct struct {
    Id           string `json:"id"`
    Name         string `json:"name"`
    UserId       string `json:"user_id"`
    CreatedAt    int64  `json:"created_at"`
}
Run Code Online (Sandbox Code Playgroud)

map[string]interface{}有按键idnameuser_idcreated_at。我需要将其转换为struct

Ble*_*ess 15

您可以为此使用https://github.com/mitchellh/mapstructure。默认情况下,它会查找标签mapstructure;因此,它可以指定很重要TagNamejson,如果你想使用JSON标签。

package main

import (
    "fmt"
    "github.com/mitchellh/mapstructure"
)

type MyStruct struct {
    Id        string `json:"id"`
    Name      string `json:"name"`
    UserId    string `json:"user_id"`
    CreatedAt int64  `json:"created_at"`
}

func main() {
    input := map[string]interface{} {
        "id": "1",
        "name": "Hello",
        "user_id": "123",
        "created_at": 123,
    }
    var output MyStruct
    cfg := &mapstructure.DecoderConfig{
        Metadata: nil,
        Result:   &output,
        TagName:  "json",
    }
    decoder, _ := mapstructure.NewDecoder(cfg)
    decoder.Decode(input)

    fmt.Printf("%#v\n", output)
    // main.MyStruct{Id:"1", Name:"Hello", UserId:"123", CreatedAt:123}
}
Run Code Online (Sandbox Code Playgroud)


irm*_*eza 5

如果我了解得很好,那么您就有一张地图,想填写struct。如果首先将其更改为jsonString,然后将其解组为struct

package main

import (
    "encoding/json"
    "fmt"
)

type MyStruct struct {
    Id           string `json:"id"`
    Name         string `json:"name"`
    UserId       string `json:"user_id"`
    CreatedAt    int64  `json:"created_at"`
}

func main() {
    m := make(map[string]interface{})
    m["id"] = "2"
    m["name"] = "jack"
    m["user_id"] = "123"
    m["created_at"] = 5
    fmt.Println(m)

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

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

}
Run Code Online (Sandbox Code Playgroud)