0

Can someone tell what is wrong with the code? I'm trying to parse the JSON from the server into variables to store the values. When i'm running the code, i'm not getting any errors. When i'm doing the print(users) after decoding the data, it's not returning anything. Can someone help me with this issue?

This is the code i'm using to retrieve the data from the server.

guard let url = URL(string: "my-url") else { return }
        let session = URLSession.shared
        let task = session.dataTask(with: url) { (data, _, _) in
            guard let data = data else { return }


            do {

                let user = try JSONDecoder().decode(User.self, from: data)
                print(user)

            } catch {}
        }
        task.resume()

JSON result from the server

{
"UserId": "55844ef7-3f05-4560-8b37-216df422ffb8",
"ContactsDto": [
    {
        "Id": null,
        "UserId": null,
        "FriendUserId": "e61d09f8-9aec-4035-b0be-c36abea2d82b",
        "FirstName": null,
        "LastName": null,
        "Email": "",
        "PhonePrefix": null,
        "Phone": "54943597",
        "InviteStatus": "pending",
        "UserStatus": null,
        "ErrorCode": 0,
        "ErrorMessage": null
    },
    {
        "Id": null,
        "UserId": null,
        "FriendUserId": "b2e0d6d7-d97c-475e-a2ab-71cb8091a7a0",
        "FirstName": null,
        "LastName": null,
        "Email": "",
        "PhonePrefix": null,
        "Phone": "207-7575",
        "InviteStatus": "pending",
        "UserStatus": null,
        "ErrorCode": 0,
        "ErrorMessage": null
    },
    {
        "Id": null,
        "UserId": null,
        "FriendUserId": "8f8d6061-3a69-4641-ac40-329a824ff4e1",
        "FirstName": null,
        "LastName": null,
        "Email": "",
        "PhonePrefix": null,
        "Phone": "58511968",
        "InviteStatus": "pending",
        "UserStatus": null,
        "ErrorCode": 0,
        "ErrorMessage": null
    },
    {
        "Id": null,
        "UserId": null,
        "FriendUserId": "40c1e461-eb98-4e18-9363-13cfa460fe7e",
        "FirstName": null,
        "LastName": null,
        "Email": "",
        "PhonePrefix": null,
        "Phone": "57864550",
        "InviteStatus": "accepted",
        "UserStatus": null,
        "ErrorCode": 0,
        "ErrorMessage": null
    }
],
"ErrorCode": 0,
"ErrorMessage": null

}

My Structure

struct User: Decodable {

let UserId: String?
let ContactsDto: [ContactsDto]?
let ErrorCode: Int?
let ErrorMessage: String?

}

struct ContactsDto : Decodable {

let Id : String?
let UserId : String?
let FriendUserId : String?
let FirstName : String?
let LastName : String?
let Email : String?
let PhonePrefix : String?
let Phone : String?
let InviteStatus : String?
let UserStatus : String?
let ErrorCode : String?
let ErrorMessage : String?

}

Ziyaad
  • 67
  • 8
  • Please try to put a breakpoint in the `print(user)` line and then write `po user` in the lldb command line, and show us the output. Try also `po user.Id` or `po user.UserId`. – Manu Mateos Nov 15 '17 at 12:29
  • Why is there `try!` inside of `do/catch`? Also example JSON is not parsable into `[[User]]`, in `User` maybe, but not in array of arrays of users. – user28434'mstep Nov 15 '17 at 12:29
  • @user28434 I removed the try! and [[User]] , still the same issue – Ziyaad Nov 15 '17 at 12:32
  • @ManuMateos Can you tell me more on how to use the lldb command line please? – Ziyaad Nov 15 '17 at 12:34
  • 1
    Now catch some error in `catch` block and print it out. – user28434'mstep Nov 15 '17 at 12:34
  • @user28434 "Thread 3: Fatal error: 'try!' expression unexpectedly raised an error: Swift.DecodingError.typeMismatch(Swift.String, Swift.DecodingError.Context(codingPath: [TestService.User.(CodingKeys in _ED50569890D0A07B17BAC874F712CE98).ContactsDto, Foundation.(_JSONKey in _12768CA107A31EF2DCE034FD75B541C9)(stringValue: "Index 0", intValue: Optional(0)), TestService.ContactsDto.(CodingKeys in _ED50569890D0A07B17BAC874F712CE98).ErrorCode], debugDescription: "Expected to decode String but found a number instead.", underlyingErro" – Ziyaad Nov 15 '17 at 12:39
  • Whelp, error says what's wrong: `ErrorCode` in `ContactsDto` declared `String?`, while it's numerical in the `JSON` – user28434'mstep Nov 15 '17 at 12:45
  • 1
    @Ziyaad Well there's your problem – `ErrorCode` isn't a `String`, it's an `Int`. Unrelated, but it's convention for property names to be `lowerCamelCase` – you can specify custom coding keys if the keys in the JSON differ (https://stackoverflow.com/q/44396500/2976878) – Hamish Nov 15 '17 at 12:45
  • @Hamish THANK YOU! It's working now – Ziyaad Nov 15 '17 at 12:48
  • @user28434 THANK YOU! It's working now – Ziyaad Nov 15 '17 at 12:48

2 Answers2

1

From looking at your code, the way you are trying to decode the JSON isn't correct.

You aren't returning an array of User, but a single User Object.

As such you could try the following:

let user = try! JSONDecoder().decode(User.self, from: data)
BlackMirrorz
  • 7,217
  • 2
  • 20
  • 31
  • 1
    I actually thought the JSON was not complete. But yes, this is a good reason :) – Manu Mateos Nov 15 '17 at 12:32
  • Thread 3: Fatal error: 'try!' expression unexpectedly raised an error: Swift.DecodingError.typeMismatch(Swift.String, Swift.DecodingError.Context(codingPath: [TestService.User.(CodingKeys in _ED50569890D0A07B17BAC874F712CE98).ContactsDto, Foundation.(_JSONKey in _12768CA107A31EF2DCE034FD75B541C9)(stringValue: "Index 0", intValue: Optional(0)), TestService.ContactsDto.(CodingKeys in _ED50569890D0A07B17BAC874F712CE98).ErrorCode], debugDescription: "Expected to decode String but found a number instead.", underlyingErro – Ziyaad Nov 15 '17 at 12:38
  • Can you provide part of your NSLog so we can help further. – BlackMirrorz Nov 15 '17 at 12:39
  • @JoshRobbins Not getting anything on my log , just this error I just updated above highlighted on my code . – Ziyaad Nov 15 '17 at 12:42
1

Based on your errors and as Josh told you in the comments, the types on your model are not correct.

For example, one of your ContactDto object is this:

{
    "Id": null,
    "UserId": null,
    "FriendUserId": "e61d09f8-9aec-4035-b0be-c36abea2d82b",
    "FirstName": null,
    "LastName": null,
    "Email": "",
    "PhonePrefix": null,
    "Phone": "54943597",
    "InviteStatus": "pending",
    "UserStatus": null,
    "ErrorCode": 0,
    "ErrorMessage": null
},

The ErrorCode type is a number (it looks like an integer), but in your model struct is a String?.

Please check every field to get all types, then fix the model and try again.

Manu Mateos
  • 174
  • 1
  • 10