I want an Error to be raised during JSON unmarshalling if an undetected field is found. This is useful if you are trying to be extra careful, for example double checking the client has not mispeled any inputs. However I want to exclude some fields from this that might be used elsewhere.Model is the struct that we are unmarshalling. We must create a new type so that the unmarshalling function is not recursive (as explained below):
type XModel Model
XModelExceptions composes the XModel with the fields we do not want to error:
type XModelExceptions struct { XModel Other *string // Other won't raise an error }
Now we define the UnmarshalJSON method for Model. This function sends its input to unmarshal a XModelExceptions struct using a json Decoder with DisallowUnknownFields() turned on. This will return an error if a field is found that is not defined in XModelExceptions.
``func (model *Model) UnmarshalJSON(data []byte) error {
var me XModelExceptions
dec := json.NewDecoder(bytes.NewReader(data))
dec.DisallowUnknownFields() // Force errors
if err := dec.Decode(&me); err != nil {
return err
}
*model = Model(me.XModel)
return nil
}``
It is important to note that If XModelExceptions was composed of Model, the unmarshalling function would be recursive and break. Hence the reason for XModel to exist.
This code can be seen working in our Odin Deployer here.