Simplified example
Lets say I have a struct which I use to unmarshall some json:
type DataEntry struct {
FirstName string `json:"first"`
LastName string `json:"last"`
FullName string
}
What I want to fill the FullName
property, which would be FirstName + LastName
.
What I am currently doing is defining a method for DataEntry, which does these kind of computations:
func (de *DataEntry) Compute() {
de.FullName = de.FirstName + " " + de.LastName
}
and calling if after the struct gets filled from the JSON:
// Grab data
request, _ := http.Get("http://........")
var entry DataEntry
dec := json.NewDecoder(request.Body)
dec.Decode(&entry)
// Compute the computed fields
entry.Compute()
Is there a better way to do this? Could I use create my own UnmarshalJSON
and use that as a trigger to automatically compute the FullName
field?