英文:
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:"id"`
Size int `json:"size"`
Rate int `json:"rate"`
Name string `json:"name"`
Komisyon int `json:"komisyon"`
}
<!-- end snippet -->
And expected response from client service as follows:
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-html -->
{
"id": 1182,
"size": 28,
"rate": 8,
"name": "Dress",
"komisyon": 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:"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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论