Search code examples
iosjsonswiftjsondecoder

How can I decode this json with Alamofire?


I want to print just value for key "User_number"

 [
   {
     "User_fullname": null,
     "User_sheba": null,
     "User_modifiedAT": "2019-01-31T18:37:02.716Z",
     "_id": "5c53404e91fc822c80e75d23",
     "User_number": "9385969339",
     "User_code": "45VPMND"
   }
 ]

Solution

  • I suppose this is some JSON in Data format

    let data = Data("""
    [ { "User_fullname": null, "User_sheba": null, "User_modifiedAT": "2019-01-31T18:37:02.716Z", "_id": "5c53404e91fc822c80e75d23", "User_number": "9385969339", "User_code": "45VPMND" } ]
    """.utf8)
    

    One way is using SwiftyJSON library, but, this is something what I don't suggest since you can use Codable.


    So, first you need custom struct conforming to Decodable (note that these CodingKeys are here to change key of object inside json to name of property of your struct)

    struct User: Decodable {
    
        let fullname, sheba: String? // these properties can be `nil`
        let modifiedAt, id, number, code: String // note that all your properties are actually `String` or `String?`
    
        enum CodingKeys: String, CodingKey {
            case fullname = "User_fullname"
            case sheba = "User_sheba"
            case modifiedAt = "User_modifiedAT"
            case id = "_id"
            case number = "User_number"
            case code = "User_code"
        }
    }
    

    then decode your json using JSONDecoder

    do {
        let users = try JSONDecoder().decode([User].self, from: data)
    } catch { print(error) }
    

    So, now you have Data decoded as array of your custom model. So if you want to, you can just get certain User and its number property

    let user = users[0]
    let number = user.number