json - 处理不同类型的请求体
问题描述
假设后端应用程序有这样的请求。如您所见,这是一个对象数组。
[
{
"section_id": "8ad1f7cc-a510-48ee-b4fa-bedbee444a84", // (uuid - string)
"section_name": "First section"
},
{
"section_id": 1556895, // (int)
"section_name": "Second section"
}
]
我想解析这个数组。根据部分 id 类型,应用程序需要做不同的事情。如何绕过严格输入?
requestBody, err := ioutil.ReadAll(request.Body)
if err = json.Unmarshal([]byte(requestBody), §ions); err != nil {
println(err)
}
for _, section := range sections {
if reflect.TypeOf(section.ID) == string {
// block 1
} reflect.TypeOf(section.ID) == int {
// block 2
}
}
解决方案
有几种方法可以做到这一点:
type Section struct {
ID interface{} `json:"section_id"`
SectionName string `json:"section_name"
}
for _, section := range sections {
if str,ok:=section.ID.(string); ok {
} else if number, ok:=section.ID.(float64); ok {
}
}
或者:
type Section struct {
ID json.RawMessage `json:"section_id"`
SectionName string `json:"section_name"
}
for _, section := range sections {
if value, err:=strconv.Atoi(string(section.ID)); err==nil {
} else {
}
}
推荐阅读
- ios - 故事板约束问题:屏幕高度的一半
- windows-10 - Windows 10 无需询问即可删除文件
- reactjs - Material-UI:模块解析失败:未终止的字符串常量 (18:5)
- angular - 类型上不存在 catchError (ret: any)
- vue.js - 当属性名称包含在值中时,Vue.js如何在html标签内输出属性?
- ios - How to attain opacity in a shape drawn in a layer of UIView that is a subView of a UIImageView?
- ansible - 尝试打印 firewalld 状态时出现 Ansible 致命错误
- arrays - Inconsistencies when removing elements from a Bash array
- java - Can I write a multithread Java program portable between pc and Android without modifying?
- python - P2P 网络:Python 套接字不接收来自其他节点的数据