Golang解析类型错误,但没有模型不匹配。

huangapple go评论78阅读模式
英文:

Golang unmarshal type error without model mismatching

问题

我有这个响应模型

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

并且客户端服务期望的响应如下:

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

但是当我进行反序列化时,Golang 给出了一个错误:unmarshal type error,并显示 komisyon 是问题所在 - 数字 21.0

当我将 komisyon 的类型从 int 改为 interface{} 时,它可以工作,但为什么 Golang 给出了这个明显是 int 的错误?如何确保其他预期的 int 值是正确的?

英文:

I have this response model

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

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

<!-- end snippet -->

And expected response from client service as follows:

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-html -->

{
          &quot;id&quot;: 1182,
          &quot;size&quot;: 28,
          &quot;rate&quot;: 8,
          &quot;name&quot;: &quot;Dress&quot;,
          &quot;komisyon&quot;: 21
}          

<!-- end snippet -->

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?

答案1

得分: 1

你收到的是浮点数,请将komisyon更改为浮点数。

英文:

you receiving float, change komisyon to float

答案2

得分: 1

似乎你的komisyon字段是21.0,它不是一个整数,你可以将其改为float64类型。

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

你可以打印val来查看在解析之前它是什么。

英文:

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:&quot;id&quot;`
	Size     int     `json:&quot;size&quot;`
	Rate     int     `json:&quot;rate&quot;`
	Name     string  `json:&quot;name&quot;`
	Komisyon float64 `json:&quot;komisyon&quot;`
}

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

huangapple
  • 本文由 发表于 2022年10月12日 06:09:49
  • 转载请务必保留本文链接:https://go.coder-hub.com/74034586.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定