[工作经验]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转化,自定义函数
代码如下:
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 协议》,转载必须注明作者和本文链接