-1

After constructed the codable, getting an error.

"msg": {
        "success": [
            "Successfully logged in."
        ]
    },
    "messages": []
}

// Constructed the codable for the parsing response data

    struct Msg:Codable{
   let success: [String]?
    enum CodingKeys: String, CodingKey{
    case success = "succcess"
    }
    init (from decoder: Decoder)throws{
    let value = try decoder.container(keyedBy: CodingKeys.self)
    sucess = try values.decodeIfPresent([String].self, forKey: .success)
    }
   }

I got this error when doing codable

erro typeMismatch(Swift.Dictionary<swift.string, Any>. Swift.DecodingError.Context ( codingPath: [CodingKeys(StringValue:"msg", intValue:nil], debugDescription: Expected to decode Dictionary <String,Any> but found an array instead."underlyingError: nil))

How to resolve this part based on server response.

Joakim Danielson
  • 43,251
  • 5
  • 22
  • 52
kiran
  • 4,285
  • 7
  • 53
  • 98
  • Your json is not an array which the error message clearly tells you, you need a top level struct for msg, `struct Root: Codable {let msg: Msg}` and then use that when decoding – Joakim Danielson Aug 07 '20 at 11:35
  • Be aware that you can omit both `init` methods and also the CodingKeys. And this can’t be the real JSON because it cannot cause this error. And if you’re responsible for the backend consider a better data structure. – vadian Aug 07 '20 at 12:43
  • Based on error description its says CodingKeys(StringValue:"msg", intValue:nil]. Never see any intValue to asign – kiran Aug 07 '20 at 12:47
  • `intValue` is `nil` because the key cannot be represented by an Int. Anyway the error has nothing to do with `intValue`. – vadian Aug 07 '20 at 12:51
  • @JoakimDanielson if forget to add { } the code inside. Its shows valid json! I do not have control on backend side. – kiran Aug 07 '20 at 12:51
  • There is no error if you implement the solution below properly so revert your question to its first version and accept the answer below. _Edit: I did the revert for you_ – Joakim Danielson Aug 07 '20 at 12:51

1 Answers1

0

This should work for you:

struct Msg: Codable {
    let success: [String]?
}

struct Response: Codable {
    let msg: Msg
}

let json = #"""
{
    "msg": {
        "success": [
            "Successfully logged in."
        ]
    },
    "messages": []
}
"""#

if let response = try? JSONDecoder().decode(Response.self, from: json.data(using: .utf8)!) {
    print(response.msg.success?.first) // Optional("Successfully logged in.")
}


iUrii
  • 11,742
  • 1
  • 33
  • 48