[英]How can mapstructure use a discriminator to decode concrete type
The docs ( https://github.com/mitchellh/mapstructure ) mention the benefits of mapstructure for decoding文档( https://github.com/mitchellh/mapstructure )提到了 mapstructure 解码的好处
{
"type": "person",
"name": "Mitchell"
}
I'm looking for an example that show the decoding process, eg to unmarshal either a Person
or Pet
class我正在寻找一个显示解码过程的示例,例如解组
Person
或Pet
类
That library only maps maps to structures.该库仅将映射映射到结构。 It does not do type-specific decoding.
它不进行特定于类型的解码。 Quoting from its doc:
引用其文档:
Perhaps we can't populate a specific structure without first reading the "type" field from the JSON.
也许我们无法在不首先从 JSON 中读取“类型”字段的情况下填充特定结构。 We could always do two passes over the decoding of the JSON (reading the "type" first, and the rest later).
我们总是可以对 JSON 的解码进行两次传递(首先读取“类型”,然后再读取其余部分)。 However, it is much simpler to just decode this into a
map[string]interface{}
structure, read the "type" key, then use something like this library to decode it into the proper structure.但是,将其解码为
map[string]interface{}
结构,读取“type”键,然后使用类似这个库的东西将其解码为正确的结构要简单得多。
All it offers is that you only have to parse the JSON source once, into a map, then you can decide yourself what type you need to map or unmarshal into.它提供的只是您只需将 JSON 源解析一次,转换为映射,然后您可以自己决定需要映射或解组为哪种类型。 Then you can use the already constructed map to fill the type you need.
然后你就可以使用已经构建好的地图来填充你需要的类型了。
See this example:看这个例子:
type Person struct {
Name string `json:"name"`
}
type Credentials struct {
User string `json:"user"`
Password string `json:"password"`
}
func main() {
for _, src := range []string{srcPerson, srcCredentials} {
var m map[string]interface{}
if err := json.Unmarshal([]byte(src), &m); err != nil {
panic(err)
}
switch m["type"] {
case "person":
var p Person
if err := mapstructure.Decode(m, &p); err != nil {
panic(err)
}
fmt.Printf("%T %+v\n", p, p)
case "credentials":
var c Credentials
if err := mapstructure.Decode(m, &c); err != nil {
panic(err)
}
fmt.Printf("%T %+v\n", c, c)
}
}
}
const srcPerson = `{
"type": "person",
"name": "Mitchell"
}`
const srcCredentials = `{
"type": "credentials",
"user": "bob",
"password": "secret"
}`
Output:输出:
main.Person {Name:Mitchell}
main.Credentials {User:bob Password:secret}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.