Home > Software engineering >  Golang unmarshal type error without model mismatching
Golang unmarshal type error without model mismatching

Time:10-13

I have this response model

type CategoryDto struct {
    ID                int                    `json:"id"`
    Size              int                    `json:"size"`
    Rate              int                    `json:"rate"`
    Name              string                 `json:"name"`
    Komisyon          int                    `json:"komisyon"`
}

And expected response from client service as follows:

{
          "id": 1182,
          "size": 28,
          "rate": 8,
          "name": "Dress",
          "komisyon": 21
}          

But when unmarshalling golang gives me error: unmarshal type error and shows; komisyon is the problem - number 21.0

When I changed komisyon int to interface{} it works but why golang gives me this error which is clearly is int. How to ensure other expected int values will be correct?

CodePudding user response:

It seems that your komisyon field is 21.0, it'is not a interger, you can change it to float64.

type CategoryDto struct {
    ID       int     `json:"id"`
    Size     int     `json:"size"`
    Rate     int     `json:"rate"`
    Name     string  `json:"name"`
    Komisyon float64 `json:"komisyon"`
}

you can print val to see what it's the before unmarshal it.

CodePudding user response:

you receiving float, change komisyon to float

  •  Tags:  
  • go
  • Related