Go 使用json标记将[string]接口{}映射到结构
我需要将键为json标记名的Go 使用json标记将[string]接口{}映射到结构,go,Go,我需要将键为json标记名的map[string]接口{}转换为struct type MyStruct struct { Id string `json:"id"` Name string `json:"name"` UserId string `json:"user_id"` CreatedAt int64 `json:"created_at"` } map[string]界面{}具有键id,name,
map[string]接口{}
转换为struct
type MyStruct struct {
Id string `json:"id"`
Name string `json:"name"`
UserId string `json:"user_id"`
CreatedAt int64 `json:"created_at"`
}
map[string]界面{}
具有键id
,name
,用户id
,在
处创建。我需要将其转换为struct
如果我理解得很好,您有一个映射,并且希望用它填充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)
}
你可以用这个。默认情况下,它查找标记mapstructure
;因此,如果要使用json标记,将标记名指定为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}
}
如果你考虑速度,那么MAPGREST会慢40%,然后在类似的结构
上测试JSONTIF.CONFITCH。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]接口{})
与您提到的非常相似的场景以及使用的原因
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
可能是@robbrit的副本谢谢你的链接。我确实尝试过该解决方案,但这要求映射的键与struct@AbA您可以调整它以满足您的需要。@Aba在前面的评论中链接的答案包含了您所需要的大部分内容。遍历字段,创建JSON名称到字段的映射。使用该映射而不是FieldByName。@Aba显示修改后的代码。我确信该方法会起作用,但如果该组件被大量使用该怎么办。这将对性能产生什么影响?它比解码快吗?如果json标记和映射不同怎么办?最好的解决方案是什么?