ava
ava

Reputation: 1176

Parsing JSON Data

I want to parse this JSON :http://jsonplaceholder.typicode.com/users I have a problem for find JSON structure. I am trying JSON with this structure that is work well, but I don't sure of this is better way or is not! what is the best way for parsing this JSON array to post instance? there is my code:

 func profileFromJSONData(data : NSData) -> ProfileResult {


         do{
        let jsonObject : NSArray!
  = try NSJSONSerialization.JSONObjectWithData(data, options: []) as! NSArray

                for profileJSON in jsonObject {
                    if let profile = profileFromJsonObject(profileJSON as! NSDictionary) {



                        finalProfile.append(profile)
                    }
                }

                return .Success(finalProfile)
            }
            catch let error {
                return .Failure(error)
            }


        }



     func profileFromJsonObject(json: NSDictionary) -> UserProfile?{

            guard let
                id = json["id"] as? Int,
                name = json["name"] as? String,
                userName = json["username"] as? String,
                email = json["email"] as? String,
                address = json["address"] as? NSDictionary,
                phone = json["phone"] as? String,
                website = json["website"] as? String,
                company = json["company"] as? NSDictionary
                else {
                    return nil
            }
            let obj = UserProfile(id: id, name: name, userName: userName, email: email, address: address, phone: phone, website: website, company: company)

            return obj
        }

Upvotes: 0

Views: 68

Answers (1)

beeth0ven
beeth0ven

Reputation: 1882

Here is what apple suggestion when Working with JSON in Swift,

and you can improve your code to one line by using flatMap

change from:

for profileJSON in jsonObject {
    if let profile = profileFromJsonObject(profileJSON) {
        finalProfile.append(profile)
    }
}

to:

finalProfile += jsonObject.flatMap(profileFromJsonObject)

That's the same.

Deal with address:

struct Address {
    var street: String
    var city: String
    ...
    init?(json: [String: AnyObject]){...}

}

extension Address: CustomStringConvertible {

    var description: String {

        return "street: \(street), city: \(city)"
    }
}

func profileFromJsonObject(json: [String: AnyObject]) -> UserProfile? {

    guard let
            ...
            addressJson = json["address"] as? [String: AnyObject]
            address = Address(json: addressJson),
            ...
            else {
                return nil
        }

    let obj = UserProfile(id: id, name: name, userName: userName, email: email, address: address, phone: phone, website: website, company: company)

    print(address) // output: "street: Kulas Light, city: Gwenborough"

}

Upvotes: 1

Related Questions