Data
type Customer struct {
Name string `json:"name"`
}
type UniversalDTO struct {
Data interface{} `json:"data"`
// more fields with important meta-data about the message...
}
func main() {
// create a customer, add it to DTO object and marshal it
customer := Customer{Name: "Ben"}
dtoToSend := UniversalDTO{customer}
byteData, _ := json.Marshal(dtoToSend)
// unmarshal it (usually after receiving bytes from somewhere)
receivedCustomer := &Customer{}
receivedDTO := UniversalDTO{Data: receivedCustomer}
json.Unmarshal(byteData, &receivedDTO)
//done
fmt.Println(receivedCustomer)
}
Dataencoding/jsoninterface{}map[string]interface{}
type Customer struct {
Name string `json:"name"`
}
type UniversalDTO struct {
Data interface{} `json:"data"`
// more fields with important meta-data about the message...
}
func main() {
// create a customer, add it to DTO object and marshal it
customer := Customer{Name: "Ben"}
dtoToSend := UniversalDTO{customer}
byteData, _ := json.Marshal(dtoToSend)
// unmarshal it (usually after receiving bytes from somewhere)
receivedDTO := UniversalDTO{}
json.Unmarshal(byteData, &receivedDTO)
//Attempt to unmarshall our customer
receivedCustomer := getCustomerFromDTO(receivedDTO.Data)
fmt.Println(receivedCustomer)
}
func getCustomerFromDTO(data interface{}) Customer {
m := data.(map[string]interface{})
customer := Customer{}
if name, ok := m["name"].(string); ok {
customer.Name = name
}
return customer
}