3 ms·
> We were unable to put default (zero) values in our config files... Huh? I don't know the details of what you're (de)serializing, but the standard strategy fo
by majewsky 9y ago
> We were unable to put default (zero) values in our config files...
Huh? I don't know the details of what you're (de)serializing, but the standard strategy for default values that are not zero values is to have unpack into a pointer. For example, if you have a message like
{ "foo": 23, "bar": 42 }
and the "bar" field has a default value of 5, you unpack like:
var msg struct {
Foo int
Bar *int
}
err := json.Unmarshal(data, &msg)
//handle error
if msg.Bar == nil {
defaultValue := 5
msg.Bar = &defaultValue
}
If you cannot change the type of the message to have a pointer field, you can implement json.Unmarshaler for the receiving type such that UnmarshalJSON deserializes into a temporary type, then copies the values into the recipient:
type Message struct {
Foo int
Bar int
}
func (m *Message) UnmarshalJSON(in []byte) error {
var msg struct {
Foo int
Bar *int
}
err := json.Unmarshal(data, &msg)
if err != nil {
return err
}
m.Foo = msg.Foo
m.Bar = 5
if msg.Bar != nil {
m.Bar = *msg.Bar
}
return nil
}
Now you can deserialize into Message (or into a struct containing a Message or *Message or []Message or whatever) and it will fill in the correct default value.