how to parse json into struct in swift
![Creative The name of the picture](https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgKPz5qhCkKGdpPJ0wkSm5JqlliSJoZg92-H4DuCruovhkVFuXerCphZt9wys_Gr3uwQyXObMHDwattjG5BSeCEl_LdDq1GPLct8qYyRyX4fZ9C93oW-TX7IGZLYDwqRgfFCXA4aUxkBAcS/s1600/1.jpg)
![Creative The name of the picture](https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEh6VebLk98DYwS3K2nWZSCatab-q4HrSuRk91M4fQA8SHrKU_-x-lq1n780pSU_bIVLqMRv6pc3dhhh-Y2PUwBS9mM0BxvY1eM6XsM-e7Diu4z-wAoeDG0vB3-2_1U9RE8sO0lg4PHiIXbI/s400/Clash+Royale+CLAN+TAG%2523URR8PPP.png)
how to parse json into struct in swift
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?
3 Answers
3
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.
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
This is for future folks. In Swift 4 there is a very nice solution with JSONDecoder
.
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!!!
guard let _
is very bad syntax if you actually need the bound variable later.– vadian
56 mins ago
guard let _
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
You can use SwiftyJSON, github.com/SwiftyJSON/SwiftyJSON
– vzamanillo
Dec 11 '14 at 11:25