ios - find objects matching id parameter in json -


i've got json contains mixture 2 kind of objects modela , modelb

modela has array contains mixture of both. modelb single item.

both modela , modelb has id parameter.

what best , fastest way find object (may modela or modelb) using id parameter , return object.

{ "id": 23,    "items":[     {   "name":"g",         "id":10     },     {         "id":90 ,         "items":[             {"name":"a" , "id":11},             {"name":"s" , "id":12},             {"id":93 , items […]},             {"name":"d" , "id":15},          ]     },     {         "id":92 ,         "items":[…]     }    ] } 

modela has id , items.

modelb has id.

items array of modela s , modelb s.

and each id unique.

thanks.

i assume have parsed json file [string: anyobject] swift dictionary.

method 1:
if going search 1 time, can recurse hierarchy using code:

func findbyid(id: int, json: [string: anyobject]) -> [string: anyobject]?{     if let jsonid = json["id"] as? int jsonid == id{         return json     }     if let jsonitems = json["items"] as? [[string: anyobject]]{         jsonitem in jsonitems{             if let item = findbyid(id, json: jsonitem){                 return item             }         }     }     return nil } 

method 2:

if going search id more once, first method become slow. have flatten json file , build dictionary ids keys , json objects(model or model b) values:

func flattenhierarchy(json: [string: anyobject], inout flatobj: [int: [string:anyobject]]){     if let jsonid = json["id"] as? int {         flatobj[jsonid] = json     }     if let jsonitems = json["items"] as? [[string: anyobject]]{         jsonitem in jsonitems{             flattenhierarchy(jsonitem, flatobj: &flatobj)         }     } }   var flatstructure = [int: [string:anyobject]]() flattenhierarchy(json, flatobj: &flatstructure) //jsonobj [string: anyobject] json  flatstructure[10] //will give result want 

Comments

Popular posts from this blog

php - How to display all orders for a single product showing the most recent first? Woocommerce -

asp.net - How to correctly use QUERY_STRING in ISAPI rewrite? -

angularjs - How restrict admin panel using in backend laravel and admin panel on angular? -