处理不同类型的请求正文

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

[
    {
        "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
    }
}
chianday 回答:处理不同类型的请求正文

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

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

,

您可以尝试以下操作:

type section struct {
    ID interface{} `json:"section_id"`
    Name string `json:"section_name"`
}

dec := json.NewDecoder(requestBody)
dec.UseNumber()
var sections []section
if err := dec.Decode([]byte(request.Body),&sections); err != nil {
    println(err)
}

for _,section := range sections {
    if reflect.TypeOf(section.ID).String() == "string" {
        // block 1
    } reflect.TypeOf(section.ID).String() == "json.Number" {
        n := section.ID.Int64()
        // block 2
    }
}
本文链接:https://www.f2er.com/3154300.html

大家都在问