相关疑难解决方法(0)

将map转换为struct

我正在尝试在Go中创建一个通用方法,它将填充struct来自a 的使用数据map[string]interface{}.例如,方法签名和用法可能如下所示:

func FillStruct(data map[string]interface{}, result interface{}) {
    ...
}

type MyStruct struct {
    Name string
    Age  int64
}

myData := make(map[string]interface{})
myData["Name"] = "Tony"
myData["Age"]  = 23

result := &MyStruct{}
FillStruct(myData, result)

// result now has Name set to "Tony" and Age set to 23
Run Code Online (Sandbox Code Playgroud)

我知道这可以使用JSON作为中介来完成; 还有另一种更有效的方法吗?

go

73
推荐指数
6
解决办法
6万
查看次数

一个字段的Golang多个json标记名称

在Golang中可以为JSON结构标记使用多个名称吗?

type Animation struct {
    Name    string  `json:"name"`
    Repeat  int     `json:"repeat"`
    Speed   uint    `json:"speed"`
    Pattern Pattern `json:"pattern",json:"frames"`
}
Run Code Online (Sandbox Code Playgroud)

tags json struct go

8
推荐指数
2
解决办法
7696
查看次数

带有自定义标签的 Golang Marshal/Unmarshal json

我想使用自定义标签编组/解组 Golang 对象 (json)。

喜欢

type Foo struct {
    Bar string `json:"test" es:"bar"`
}

data, _ := json.MarshalWithESTag(Foo{"Bar"})
log.Println(string(data)) // -> {"foo":"bar"}
Run Code Online (Sandbox Code Playgroud)

换句话说,我想在这里使用带有不同标签的encoding/json库: https: //github.com/golang/go/blob/master/src/encoding/json/encode.go#L1033

谢谢 :)

json go

7
推荐指数
1
解决办法
9195
查看次数

标签 统计

go ×3

json ×2

struct ×1

tags ×1