2 回答

TA貢獻(xiàn)1806條經(jīng)驗 獲得超5個贊
你可以嘗試用這個:
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), §ions); 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
}
}

TA貢獻(xiàn)1827條經(jīng)驗 獲得超8個贊
有幾種方法可以做到這一點:
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 {
}
}
- 2 回答
- 0 關(guān)注
- 158 瀏覽
添加回答
舉報