解组DTO之前,请将
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)}
如果您无法
Data在解组前在DTO上初始化字段,则可以在解组后使用类型断言。
encoding/json将
interface{}类型值unamrshals
打包到中
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}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)