Uploaded image for project: 'Swift'
  1. Swift
  2. SR-9023

Decoding a JSON Dictionary with a UUID key either doesn't work, or shows the wrong error message

    XMLWordPrintable

    Details

    • Type: Bug
    • Status: Open
    • Priority: Medium
    • Resolution: Unresolved
    • Component/s: Foundation
    • Labels:
    • Environment:

      I ran the code in a Playground file and in an iOS app as well.
      Xcode Version: 10.0 (10A255)
      macOS Version: 10.14 (18A391)
      Swift Version: 4.2

      Description

      Consider the following attempt to deserialise JSON:

       import UIKit
      
      let json = """
       {
           "localisedTexts": {
               "454198ea-bee1-49ac-a8b9-1ceaf8220a85": {
                   "EN-US": "What is your name?", "EN-UK": "What is your name?"
               }
            }
       }
       """.data(using: .utf8)!
      
      struct MyStruct: Codable {
         let localisedTexts: Dictionary<UUID, Dictionary<String, String>> 
      }
      
      let jsonDecoder = JSONDecoder()
      
      do {
          let x = try jsonDecoder.decode(MyStruct.self, from: json)
          print(x)
      } catch let err {
         print(err)
      }
      

      I would expect my object to get deserialised from the json. Instead, I get this error message:
      typeMismatch(Swift.Array<Any>, Swift.DecodingError.Context(codingPath: [CodingKeys(stringValue: "localisedTexts", intValue: nil)], debugDescription: "Expected to decode Array<Any> but found a dictionary instead.", underlyingError: nil))


      Here's some other things I've tried:

      • Changing `let localisedTexts: Dictionary<UUID, Dictionary<String, String>>` to `let localisedTexts: Dictionary<String, Dictionary<String, String>>` deserialises my object just fine.
      • Changing `UUID` to `Int` for the key (and changing the JSON correspondingly) works too.

      I've attached a playground file for illustrative purpose.

        Attachments

          Issue Links

            Activity

              People

              • Assignee:
                itaiferber Itai Ferber
                Reporter:
                mayurdhaka.swift Mayur Dhaka
              • Votes:
                1 Vote for this issue
                Watchers:
                4 Start watching this issue

                Dates

                • Created:
                  Updated: