Custom unmarshaling with two passes
The first pass unmarshals discriminator fields while leaving the rest of the input unprocessed. Based on the discriminator, the concrete instance of the object is constructed and unmarshaled.
How to do it...
- We will work with an example
Key
structure in this section. TheKey
structure holds different types of cryptographic public keys, whose type is given in aType
field:type KeyType string const ( KeyTypeRSA = "rsa" KeyTypeED25519 = "ed25519" ) type Key struct { Type KeyType `json:"type"` Key crypto.PublicKey `json:"key"` }
- Define the JSON tags for the data structure as usual. Most polymorphic structures can be marshaled without a custom marshaler because the runtime type of objects...