json - Initialize Swift class with AnyObject? from NSJSONSerialization -


i using nsjsonserialization in swift 1.2 parse json returned api response.

var err: nserror? let opts = nsjsonreadingoptions.allowfragments let json: anyobject? = nsjsonserialization.jsonobjectwithdata(jsondata!, options: opts, error: &err) 

the parsed json provided anyobject?. use optional initialize class object can used model data in application.

class alerts {     let type: string     let date: string     let description: string     let expires: string     let message: string      init(json: anyobject) {         if let         jsondict = json as? [string: anyobject],         alertsarray = jsondict["alerts"] as? [anyobject],         alertsdict = alertsarray[0] as? [string: anyobject],         type = alertsdict["type"] as? string,         date = alertsdict["date"] as? string,         description = alertsdict["description"] as? string,         expires = alertsdict["expires"] as? string,         message = alertsdict["message"] as? string         {             self.type = type             self.date = date             self.description = description             self.expires = expires             self.message = message         }         else         {             self.type = "err"             self.date = "err"             self.description = "err"             self.expires = "err"             self.message = "err"         }     } }  // example of creating data model json let alerts = alerts(json: json!) alerts.type alerts.date alerts.description alerts.expires alerts.message 

since nsjsonserialization returns optional, have check existence of each value type extract json data. can see in above code, used improved optional bindings swift 1.2 clean init method. without using third-party libraries, there else can class model (enums, structs, type aliases) make more readable? should use struct model data instead of class? possible create custom type using enum or struct represent json object?

so without using third party libraries, if let trees best practice, have shown. later down road, maybe recreate object hierarchy in json struct model in swift. like:

var json = json(jsondata.sharedjson.jsonraw!) var mongoidtest = json["resultset"]["account"]["mongoid"].string  struct root {     var timestamp: int?     var resultset = resultset()      init() {         self.timestamp = json["timestamp"].int         println(json)     }  }  struct resultset {     var alert: string?      var account = account()     var customer = customer()      init() {      }   }  struct account {     var mongoid: string?      init() {         mongoid = json["resultset"]["account"]["mongoid"].string     } }  struct locations {  }  struct customer {     var account: string?     var address: string?     var id: string?     var loginid: string?     var mongoid: string?     var name: string?      var opco = opco()      init() {         account = json["resultset"]["customer"]["account"].string         address = json["resultset"]["customer"]["address"].string         id = json["resultset"]["customer"]["id"].string         loginid = json["resultset"]["customer"]["loginid"].string         mongoid = json["resultset"]["customer"]["mongoid"].string         name = json["resultset"]["customer"]["name"].string     }  }  struct opco {     var id: string?     var phone: string?     var cutofftime: string?     var name: string?     var payerid: string?      init() {         id = json["resultset"]["customer"]["opco"]["id"].string         phone = json["resultset"]["customer"]["opco"]["phone"].string         cutofftime = json["resultset"]["customer"]["opco"]["cutofftime"].string         name = json["resultset"]["customer"]["opco"]["name"].string         payerid = json["resultset"]["customer"]["opco"]["payerid"].string     } } 

this way can still use autocomplete , dot notation navigate through hierarchy.

edit: have data structure actual project i've worked on added answer, gives better idea. keep in mind i'm using swiftyjson json() call.

edit 2:

this method found getting json info swift dictionary without use of other library. i'm not sure there way that's easier without use of third party libraries.

var urltorequest = "https://example.com/api/account.login?username=my_username&password=hunter2"  if let json = nsdata(contentsofurl: nsurl(string: urltorequest)!) {      // parse json dictionary     var error: nserror?     let boardsdictionary = nsjsonserialization.jsonobjectwithdata(json, options: nsjsonreadingoptions.mutablecontainers, error: &error) as? dictionary<string, anyobject>     fulljson = boardsdictionary      // display keys , values     println("keys in user data:")     (key, value) in boardsdictionary! {         println("\(key)-------\(value)")     }      println(fulljson?["resultset"]) } else {     println("test json nil: no connection?") } 

that dictionary input structs.


Comments