首页 > 解决方案 > 处理不同类型的请求体

问题描述

假设后端应用程序有这样的请求。如您所见,这是一个对象数组。

[
    {
        "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), &sections); err != nil {
    println(err)
}

for _, section := range sections {
    if reflect.TypeOf(section.ID) == string {
        // block 1
    } reflect.TypeOf(section.ID) == int {
        // block 2
    }
}

标签: jsongoreflection

解决方案


有几种方法可以做到这一点:

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 {
   }
}


推荐阅读