map [string] interface {} to struct with json tags

时间:2018-02-26 17:33:19

标签: go

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

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

map[string]interface{}包含密钥idnameuser_idcreated_at。我需要将其转换为struct

3 个答案:

答案 0 :(得分:1)

如果我理解得很好,您有一张地图,想填写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)

}

答案 1 :(得分:0)

您可以使用https://github.com/mitchellh/mapstructure。默认情况下,它会寻找标签mapstructure;因此,如果要使用json标签,请务必将TagName指定为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}
}

答案 2 :(得分:0)

如果你考虑速度,那么 Mapstructure 比 jsoniter.ConfigFastest 慢 40%,在那里你测试类似的结构

type Message struct {
    ID        string      `json:"id,omitempty"`
    Type      string      `json:"type"`
    Timestamp uint64      `json:"timestamp,omitempty"`
    Data      interface{} `json:"data"`
}

并且您想通过 Type == "myType" 检查消息类型,然后仅编组/解组数据字段(在第一次解组后将是 map[string]interface{}) 与您提到的情况非常相似,以及使用 https://github.com/mitchellh/mapstructure 的原因...

goos: windows
goarch: amd64
cpu: AMD Ryzen Threadripper 3960X 24-Core Processor 
BenchmarkMarshalUnmarshal
BenchmarkMarshalUnmarshal-48                      521784          2049 ns/op         871 B/op         20 allocs/op
BenchmarkMarshalUnmarshalConfigFastest
BenchmarkMarshalUnmarshalConfigFastest-48         750022          1591 ns/op         705 B/op         15 allocs/op
BenchmarkMapstructure
BenchmarkMapstructure-48                          480001          2546 ns/op        1225 B/op         25 allocs/op
BenchmarkDirectStruct
BenchmarkDirectStruct-48                         3096033           391.7 ns/op        88 B/op          3 allocs/op
PASS