Parsing JSON in swift 2.0 -


i'm trying parse json data server api. json :

    [  {"interest": {  "title":"sport",  "sub":[         "painting",         "photography",         "museum"]  }  },  {"interest": {  "title": "music",  "sub": [          "rock",          "classic",          "techno"]  }  }] 

the code file test parse :

do{             let path = nsbundle.mainbundle().pathforresource("maininterest", oftype: "json")             let jsondata = nsdata(contentsoffile: path!)             let jsonresult:nsarray!  = try nsjsonserialization.jsonobjectwithdata(jsondata! , options: nsjsonreadingoptions.mutablecontainers) as! nsarray          } catch let error nserror {             print(error)         } 

i can access whole file :

print(jsonresult) 

but can't access more 1 level, here first level :

if let = jsonresult {          print(a[0]["interest"])     } 

i can first object file, i access jsonresult[0]["interest"]["title"] (==sport) or jsonresult[0]["interest"]["sub"][2] (== photography) have kind of error build failed:

    cannot subscript value of type 'anyobject?!' index of type 'string' cannot subscript value of type 'anyobject?!' index of type 'int' 

could please me ? i'm stuck , apple doc not explicite on point think. , don't want use framework swiftyjson etc.

thanks lot ! ben

edit :

solved (thanks @maxpovver) :

//to title         let title = (((self.interests nsarray)[0] as? nsdictionary)?["interest"] as? nsdictionary)?["title"] as? nsstring         print(title)         //to sub         let sub = ((((self.interests nsarray)[0] as? nsdictionary)?["interest"] as? nsdictionary)?["sub"] as! nsarray)[1] as! nsstring 

the answer

//to title     let title = (((self.interests array)[0] as? dictionary)?["interest"] as? dictionary)?["title"] as? string     print(title)     //to sub     let sub = ((((self.interests array)[0] as? dictionary)?["interest"] as? dictionary)?["sub"] as! array)[1] as! string 

also can made more readable:

let firstinterest = ((self.interests array)[0] as? dictionary)?["interest"] as? dictionary)? let title = firstinterest?["title"] as? string let sub = (firstinterest?["sub"] as! array)[1] as! string 

you'll never ablo simplify without libraries swift not support dynamic types.


Comments

Popular posts from this blog

javascript - Karma not able to start PhantomJS on Windows - Error: spawn UNKNOWN -

Nuget pack csproj using nuspec -

c# - Display ASPX Popup control in RowDeleteing Event (ASPX Gridview) -