简体   繁体   English

mapstructure 如何使用鉴别器来解码具体类型

[英]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我正在寻找一个显示解码过程的示例,例如解组PersonPet

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.

相关问题 如果该具体类型在运行时存储在 'Decodable.Type' 变量中,您如何解码已知的具体类型? - How do you decode a known, concrete type if that concrete type is stored in a variable of 'Decodable.Type' at runtime? 如何在Elm 0.17中对具体类型进行http请求和解码响应? - How to make http request and decode response to concrete type in Elm 0.17? mapstructure 将 map[string]interface{} 解码为包含自定义类型的结构给出错误 - mapstructure decode a map[string]interface{} into a struct containing custom type gives Error 您能否将子 JSON 对象解码为其字符串表示而不是具体类型? - Can you decode a child JSON object into its string representation instead of a concrete type? 如何使用JSONDecoder解码未知类型的JSON? - How to use JSONDecoder to decode JSON with unknown type? 如何指示Json.NET将接口类型转换为具体类型而无需访问序列化程序? - How can I instruct Json.NET to convert an interface type to a concrete type without access to the serializer? 在MVC4中使用WebApi,如何将动态json反序列化为具体类型? - Using WebApi in MVC4, how can I deserialize dynamic json to a concrete type? 如何使用json解码 - how to use json to decode 找不到非具体Collection类型的反序列化 - Can not find deserialize for non-concrete Collection type 我可以将json解析为字符串或其他具体类型作为对象吗? - Can I parse json either into a string or another concrete type as object?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM