[工作经验]go, json 接收string 转为int

场景

如下json

"{\"RetCode\":200,\"Message\":\"查询成功!\",\"Data\":{\"List\":[{\"ProjectSubjectId\":\"1234520221026001\",\"ProjectId\":\"12345\",\"ProjectNo\":\"test111\",\"GcpCode\":\"2022YL01\",\"IsActive\":1,\"Age\":\"30\",\"Phone\":\"13511111111\",\"Urgent_phone\":\"\",\"Address\":\"测试地址111\",\"HisPatientNo\":\"20221026001\",\"PatientName\":\"张三\",\"PatientIdentifyNo\":\"430502199709226522\",\"Sex\":\"1\",\"BirthDate\":\"1997-09-22\"},{\"ProjectSubjectId\":\"1234520221026002\",\"ProjectId\":\"12345\",\"ProjectNo\":\"test111\",\"GcpCode\":\"2022YL01\",\"IsActive\":1,\"Age\":\"31\",\"Phone\":\"17523659963\",\"Urgent_phone\":\"\",\"Address\":\"测试地址222\",\"HisPatientNo\":\"20221026002\",\"PatientName\":\"王五\",\"PatientIdentifyNo\":\"430511197501253622\",\"Sex\":\"1\",\"BirthDate\":\"1975-01-25\"},{\"ProjectSubjectId\":\"112234\",\"ProjectId\":\"12346\",\"ProjectNo\":\"test222\",\"GcpCode\":\"2022YL02\",\"IsActive\":1,\"Age\":\"35\",\"Phone\":\"13511111112\",\"Urgent_phone\":\"\",\"Address\":\"测试333\",\"HisPatientNo\":\"20221026003\",\"PatientName\":\"李四\",\"PatientIdentifyNo\":\"430511198501253622\",\"Sex\":\"2\",\"BirthDate\":\"2022-06-13\"}]},\"Count\":2,\"PageIndex\":1,\"PageSize\":10000}"

json返回 age是string
但是我age结构体,是定义为 int的。

且,因为某些问题,不同厂商,公用这个结构体,所以结构体类型还不能换。

那么只能解析时候定义 函数了。

定义json转化,自定义函数

【工作经验】go, json 接收string 转为int

代码如下:

type TestAge string

func (t *TestAge) MarshalJSON() ([]byte, error) {
    if *t != "" {

        tInt, _ := strconv.Atoi(string(*t))

        return []byte(fmt.Sprintf(`%d`, tInt)), nil
    }
    return []byte(fmt.Sprintf(`%d`, 0)), nil
}
本作品采用《CC 协议》,转载必须注明作者和本文链接
嗨,我是波波。曾经创业,有收获也有损失。我积累了丰富教学与编程经验,期待和你互动和进步! 公众号:上海PHP自学中心 付费知识星球:破解面试:程序员的求职导师
讨论数量: 0
(= ̄ω ̄=)··· 暂无内容!

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!
司机 @ 欣昊玉
文章
273
粉丝
339
喜欢
557
收藏
1103
排名:64
访问:12.1 万
私信
所有博文
社区赞助商