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?

Leo Dabus
  • 229,809
  • 59
  • 489
  • 571
lionlinekz
  • 83
  • 1
  • 1
  • 8

3 Answers3

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!!!

Kanishk Gupta
  • 369
  • 2
  • 10
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.

Community
  • 1
  • 1
Lars Christoffersen
  • 1,719
  • 13
  • 24
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
Binglin
  • 74
  • 5