我一直在研究一種嘗試解析嵌套 JSON 響應(yīng)而不將信息映射到預(yù)定義結(jié)構(gòu)的方法。使用空白界面,它返回為:map[name:My Folder parentId:1 created:2014-10-09T16:32:07+0000 deleted:false description:Sync Dir id:3 links:[map[rel:self entity:folder href:https://web .domain.org/rest/folders/3 id:3] map[href:https://web.domain.org/rest/folders/1 id:1 rel:parent entity:folder] map[entity:user href: https://web.domain.org/rest/users/1 id:1 rel:creator]] 修改時間:2014-12-18T18:07:01+0000 固定鏈接:https://web.domain.org/w/ SpJYGQkv syncable:true type:d userId:1]所以我使用以下內(nèi)容來瀏覽這些信息:func NFind(input interface{}, refs...interface{}) (output interface{}) { defer func() {if r := recover(); r != nil { output = nil }}() for _, ref := range refs { switch cur := ref.(type) { case string: output = input.(map[string]interface{})[cur] case int: output = input.([]interface{})[cur] } } return output}func NMap(input interface{}) (output map[string]interface{}) { defer func() {if r := recover(); r != nil {}}() if input == nil { return nil } return input.(map[string]interface{})}func NArray(input interface{}) (output []interface{}) { defer func() {if r := recover(); r != nil {}}() if input == nil { return nil } return input.([]interface{})}func NString(input interface{}) (output string) { defer func() {if r := recover(); r != nil {}}() if input == nil { return "" } return input.(string)}func NFloat64(input interface{}) (output float64) { defer func() {if r := recover(); r != nil {}}() if input == nil { return 0 } return input.(float64)} 這是從 JSON 字符串解析信息的可接受方式,還是有更可取的方法?以下是使用上述內(nèi)容解析出我當(dāng)前使用的正確信息的示例:func mapCache(input map[string]interface{}, valType string) { fmt.Println(input) var ( name string href string rel string links []interface{} myMap map[string]interface{} )
可以使用恐慌/恢復(fù)作為測試成功類型斷言的手段嗎?
慕田峪4524236
2021-09-10 10:58:01