如何将JSON文档中的字符串值解组为一个int类型的变量? [英] How do I unmarshal a string value from a JSON document into a variable of type int?

查看:831
本文介绍了如何将JSON文档中的字符串值解组为一个int类型的变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的结构:

 类型User结构{
名字字符串`json:firstname,omitemptyvalidate:
LastName字符串`json:lastname,omitemptyvalidate:required`
NumberofDays int`json:numberofdays,stringvalidate:min = 0,max = 100`

NumberofDays的值作为字符串从服务器传递,但我想检查是否它在范围内并以int的形式存储。



例如: user:=& User {Michael,Msk,3}



我得到'不能将字符串解组为'int类型的Go值'。



我不确定如何对int进行类型转换并进行验证

解决方案

删除结构标记中的逗号后的空格,例如 json:numberofdays,string应该是 json:numberofdays,string。有了空格, json 包将忽略字符串部分,因此会出现错误消息。如果没有空间,错误就会消失,行为也会如预期。

p / AUImnw_PISrel =nofollow noreferrer> https://play.golang.org/p/AUImnw_PIS



json package struct tags: https://golang.org/ pkg / encoding / json /#Marshal


My struct:

type User struct {
    FirstName     string `json:"firstname, omitempty" validate:"required"` 
    LastName      string `json:"lastname, omitempty" validate:"required"`
    NumberofDays  int   `json:"numberofdays, string" validate:"min=0,max=100"`
}

Value for NumberofDays is passed as string from the server but I want to check if it is within range and store as int.

Ex: user := &User{"Michael","Msk","3"}

I'm getting 'cannot unmarshal string into Go value of type int'.

I'm not sure how to typecast to int and do the validation

解决方案

Remove the space after the comma in the struct tags, e.g. json:"numberofdays, string" should be json:"numberofdays,string". With the space, the json package ignores the string part, hence the error message you're getting. Without the space, the error goes away and behavior is as expected.

Demo comparing the two here: https://play.golang.org/p/AUImnw_PIS

Documentation of json package struct tags: https://golang.org/pkg/encoding/json/#Marshal

这篇关于如何将JSON文档中的字符串值解组为一个int类型的变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆