Golang将接口{}转换为struct

Golang将接口{}转换为struct,第1张

Golang将接口{}转换为struct

解组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}


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5170834.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-11-18
下一篇 2022-11-18

发表评论

登录后才能评论

评论列表(0条)

保存