Golang convert interface{} to struct

前端 未结 1 558
星月不相逢
星月不相逢 2021-02-04 09:22

I want to improve the getCustomerFromDTO method in the code below, I need to create a struct from an interface{} and currently i need to marshall that interface to byte[] and th

相关标签:
1条回答
  • 2021-02-04 09:32

    Before unmarshaling the DTO, set the Data field to the type you expect.

    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)
    }
    

    If you don't have the ability to initialize the Data field on the DTO before it's unmarshaled, you can use type assertion after the unmarshaling. Package encoding/json unamrshals interface{} type values into a map[string]interface{}, so your code would look something like this:

    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 讨论(0)
提交回复
热议问题