swift - Parsing JSON into a usable format -


i'm downloading data server , i'm not sure how response i'm getting format that's expected method i'm working with. guide me on need of items in json response added [[string : anyobject]] format?

thank in advance!!

json i'm getting back

{     "green shirt": [         {             "id": "740",             "name": “nice green shirt",             "quantity": "0",             "make": "",             "model": "",             "price": “15.00",             "size": "xxs",             "sku": null,             "image": "https:\/\/google.com\/green_shirt.jpg",             "new_record": false,             "category_name": "",             "bar_code": "",         },         {             "id": "743",             "name": "green shirt",             "quantity": “68",             "make": "",             "model": "",             "price": “20.00",             "size": "xs",             "sku": null,             "image": "https:\/\/google.com\/green_shirt.jpg",             "new_record": false,             "category_name": "",             "bar_code": "",         }     ],     "dark blue jeans": [         {             "id": "1588",             "name": "dark blue jeans",             "quantity": "0",             "make": "",             "model": "",             "price": "0.00",             "size": “s",             "sku": null,             "image": "https:\/\/google.com\/dark_blue_jeans.jpg",             "new_record": false,             "category_name": "",             "bar_code": "",             "category": null         },         {             "id": "1559",             "name": "dark blue jeans",             "quantity": "4",             "make": "",             "model": "",             "price": "0.00",             "size": “xl",             "sku": null,             "image": "https:\/\/google.com\/dark_blue_jeans.jpg",             "new_record": false,             "category_name": "",             "bar_code": "",             "category": null         }     ],     "white belt": [         {             "id": "1536",             "name": "white belt",             "quantity": "37",             "make": "",             "model": "",             "price": "0.00",             "size": "one size",             "sku": null,             "image": "https:\/\/google.com\/white_belt.jpg",             "new_record": false,             "category_name": "",             "bar_code": "",             "category": null         }     ] } 

what i'm trying take items in "green shirt", "dark blue jeans" , "white belt" , put them in format [[string : anyobject]]

// 1 - make http request var endpoint = nsurl(string: "https://www.mycustomsite.com/get-inventory") var data = nsdata(contentsofurl: endpoint!)   // 2 - validate , deserialize response  if let json: nsdictionary = nsjsonserialization.jsonobjectwithdata(data!, options: nsjsonreadingoptions.mutablecontainers, error: nil) as? nsdictionary {   } 

the trick declare right type cast.

for data using [string: [[string: anyobject]]]: dictionary string key , array of dictionaries value, these dictionaries have value anyobject because there's several possible types.

after successful decoding, print resulting dictionary (result 1).

then, example, loop on dictionaries contained in array behind key "green shirt", , display id , size.

and last example: array clothes objects.

if let json = nsjsonserialization.jsonobjectwithdata(data!, options: nsjsonreadingoptions.allzeros, error: nil) as? [string: [[string: anyobject]]] {      // result 1     println(json)      // example of how parse data     if let allgreenshirts = json["green shirt"] {         greenshirt in allgreenshirts {             if let id = greenshirt["id"] as? string, let size = greenshirt["size"] as? string {                 println("id \(id) of size \(size)")             }         }     }      // if want array of clothes, populate array of dictionaries:     var allclothes = [[string:anyobject]]()     (_, clothes) in json {         allclothes += clothes     }      println(allclothes)  } 

result 1:

[white belt: [[size: 1 size, price: 0.00, category: , make: , model: , image: https://google.com/white_belt.jpg, category_name: , new_record: 0, name: white belt, sku: , id: 1536, quantity: 37, bar_code: ]], green shirt: [[size: xxs, price: 15.00, sku: , name: nice green shirt, id: 740, make: , model: , image: https://google.com/green_shirt.jpg, category_name: , quantity: 0, bar_code: , new_record: 0], [size: xs, price: 20.00, sku: , name: green shirt, id: 743, make: , model: , image: https://google.com/green_shirt.jpg, category_name: , quantity: 68, bar_code: , new_record: 0]], dark blue jeans: [[size: s, price: 0.00, category: , make: , model: , image: https://google.com/dark_blue_jeans.jpg, category_name: , new_record: 0, name: dark blue jeans, sku: , id: 1588, quantity: 0, bar_code: ], [size: xl, price: 0.00, category: , make: , model: , image: https://google.com/dark_blue_jeans.jpg, category_name: , new_record: 0, name: dark blue jeans, sku: , id: 1559, quantity: 4, bar_code: ]]]

example:

id 740 of size xxs
id 743 of size xs

array of clothes:

[[size: 1 size, price: 0.00, category: , make: , model: , image: https://google.com/white_belt.jpg, category_name: , new_record: 0, name: white belt, sku: , id: 1536, quantity: 37, bar_code: ], [size: xxs, price: 15.00, sku: , name: nice green shirt, id: 740, make: , model: , image: https://google.com/green_shirt.jpg, category_name: , quantity: 0, bar_code: , new_record: 0], [size: xs, price: 20.00, sku: , name: green shirt, id: 743, make: , model: , image: https://google.com/green_shirt.jpg, category_name: , quantity: 68, bar_code: , new_record: 0], [size: s, price: 0.00, category: , make: , model: , image: https://google.com/dark_blue_jeans.jpg, category_name: , new_record: 0, name: dark blue jeans, sku: , id: 1588, quantity: 0, bar_code: ], [size: xl, price: 0.00, category: , make: , model: , image: https://google.com/dark_blue_jeans.jpg, category_name: , new_record: 0, name: dark blue jeans, sku: , id: 1559, quantity: 4, bar_code: ]]

note our mapping, can create allclothes flatmap instead of making loop:

let allclothes = flatmap(json, { $1 }) 

so, conclude, here's our functions included in class example of how use it.

class datamanager {      typealias myjsondic = [string: [[string: anyobject]]]      func getclothesdictionaryfromjson(data: nsdata) -> myjsondic? {         if let json = nsjsonserialization.jsonobjectwithdata(data, options: nsjsonreadingoptions.allzeros, error: nil) as? myjsondic {             return json         }         return nil     }      func shirtssizes(json: myjsondic, category: string) -> [string] {         var shirts = [string]()         if let allshirtsincategory = json[category] {             shirt in allshirtsincategory {                 if let id = shirt["id"] as? string, let size = shirt["size"] as? string {                     shirts.append("id \(id) of size \(size)")                 }             }         }         return shirts     }      func getallclothes(json: myjsondic) -> [[string: anyobject]] {         return flatmap(json, { $1 })     }  }  let manager = datamanager() let clothesdictionary = manager.getclothesdictionaryfromjson(data!) let greenshirtssizes = manager.shirtssizes(clothesdictionary!, category: "green shirt") let allclothes = manager.getallclothes(clothesdictionary!) 

note in class example we've created typealias type of our dictionary, it's more convenient write , read.

swift 2 update

class datamanager {      typealias myjsondic = [string: [[string: anyobject]]]      func getclothesdictionaryfromjson(data: nsdata) -> myjsondic? {         {             if let json = try nsjsonserialization.jsonobjectwithdata(data, options: []) as? myjsondic {                 return json             }         } catch let error nserror {             print(error)         }         return nil     }      func shirtssizes(json: myjsondic, category: string) -> [string] {         var shirts = [string]()         if let allshirtsincategory = json[category] {             shirt in allshirtsincategory {                 if let id = shirt["id"] as? string, let size = shirt["size"] as? string {                     shirts.append("id \(id) of size \(size)")                 }             }         }         return shirts     }      func getallclothes(json: myjsondic) -> [[string: anyobject]] {         return json.flatmap { $1 }     }  }  let manager = datamanager() if let data = data, let clothesdictionary = manager.getclothesdictionaryfromjson(data) {     let greenshirtssizes = manager.shirtssizes(clothesdictionary, category: "green shirt")     let allclothes = manager.getallclothes(clothesdictionary)     print(greenshirtssizes)     print(allclothes) } 

Comments

Popular posts from this blog

PHP DOM loadHTML() method unusual warning -

python - How to create jsonb index using GIN on SQLAlchemy? -

c# - TransactionScope not rolling back although no complete() is called -