ugorji / go

idiomatic codec and rpc lib for msgpack, cbor, json, etc. msgpack.org[Go]
MIT License
1.85k stars 295 forks source link

Q: Decode value in a field into different types depending on a value in another field #277

Closed ken5scal closed 5 years ago

ken5scal commented 5 years ago

This question is a bit similar to #138. I want to decode a value which would have a different structure based on another field. For example, say I have SomeObject in which Statement field can use multiple structures depending on Fmt value. In other words, you would not know the structure of Statement until Fmt value is evaluated. Would ugorji/go/codec be able to carry out such decoding?

type SomeObject struct {
    Fmt string `codec:"fmt"`
    Statement  {the struct can be either StmtOne or StmtTwo based on fmt} `codec:"stmt"`
}

type StmtOne struct {
    Ver      string `codec:"ver"` 
    Response []byte `codec:"response"` 
}

type StmtTwo struct {
    X5c      string `codec:"x5c"` 
    Sigs []byte `codec:"signatures"` 
}
ugorji commented 5 years ago

You can make this work, but it is not natively supported by the library. This means you have to write some code to do this, leveraging what the library provides.

Currently, the library assumes that you know the structure of what you want to decode into, or it will allow you decode into a generic container (e.g. map, slice, etc). The only escape hatch is the "Raw" type.

Your best bet might be one of the following:

Hope this helps.