简体   繁体   English

如何将JSON快速解析为结构

[英]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. 我想从JSON解析一组公司。

Can you please help me how can I do that in Swift? 您能帮我在Swift中怎么做吗?

This is for future folks. 这是给未来的人们的。 In Swift 4 there is a very nice solution with JSONDecoder . 在Swift 4中, JSONDecoder是一个非常好的解决方案。

With Alamofire code will look like this - 使用Alamofire的代码将如下所示-

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://developer.apple.com/documentation/foundation/jsondecoder

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

Hope this helps!!! 希望这可以帮助!!!

Unfortunately JSON parsing is not very easy in swift. 不幸的是,JSON解析并不是一件容易的事。 You should use the NSJSONSerialization class to do it. 您应该使用NSJSONSerialization类来做到这一点。

There are plenty of examples here to look at. 这里有很多示例可供参考。

In Swift3, It's possible to convert dictionary direct to struct use MappingAce 在Swift3中,可以使用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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM