1

I have struct like this:

struct Company {

    let name:String
    let id:Int
} 

I want to parse from JSON a set of Companies.

Can you please help me how can I do that in Swift?

1

3 Answers 3

1

This is for future folks. In Swift 4 there is a very nice solution with JSONDecoder.

With Alamofire code will look like this -

Alamofire.request(Router.login(parameters: parameters)).responseJSON {
        response in
        switch response.result{
        case .success(_):
            let decoder = JSONDecoder()
            guard let _ = response.data else{
                return
            }
            do {
                let loginDetails = try decoder.decode(LoginDetails.self, from: response.data!)
                // get your details from LoginDetails struct
            } catch let err{
                print(err)
            }


        case .failure(let error):
            print(error)
        }
    }

https://developer.apple.com/documentation/foundation/jsondecoder

https://medium.com/xcblog/painless-json-parsing-with-swift-codable-2c0beaeb21c1

Hope this helps!!!

Sign up to request clarification or add additional context in comments.

2 Comments

guard let _ is very bad syntax if you actually need the bound variable later.
I think the point here is how to decode a JSON to a struct. You can unwrap the optional whichever way you want.
0

Unfortunately JSON parsing is not very easy in swift. You should use the NSJSONSerialization class to do it.

There are plenty of examples here to look at.

Comments

0

In Swift3, It's possible to convert dictionary direct to struct use MappingAce

struct Company: Mapping {
    let name:String
    let id:Int
}

let companyInfo: [String : Any] = ["name" : "MappingAce", "id" : 1]

let company = Company(fromDic: companyInfo)
print(company.name)//"MappingAce"
print(company.id)  // 1

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.