简体   繁体   中英

How to convert JSON response to Dictionary format in Swift

How do I convert this JSON response with hundreds of keys in message, to be able to assign it to a variable type [AnyHashable: Any]

JSON

{
    "content": {
       "message": {
            "greet": "Hello world",
            "error": "There is an error",
            "thanks": "Thank you",
            ...
        }
    }
}

Attempt

After I've parse the JSON, I've failed to assign jsonData to a variable that accept [AnyHashable: Any] . I have tried to change message type to [AnyHashable: Any] but it does not conform to Decodable .

// Model.swift

struct TestCase: Decodable {
    let content: Content
}

struct Content: Decodable {
    let message: [String: String]
}


// ViewController.swift

private var testVariable: [AnyHashable: Any]

private func loadJson(filename: String) {
    if let url = Bundle.main.url(forResource: filename, withExtension: "json") {
        do {
            let data = try Data(contentsOf: url)
            let decoder = JSONDecoder()
            let jsonData = try decoder.decode(TestCase.self, from: data)

            // Problem faced
            testVariable = jsonData // error

        } catch let jsonError {
            print("JsonError: ", jsonError)
        }
    }
}

You cannot have both.

Either you want to parse the JSON with Decodable then you have to declare testVariable as

private var testVariable : TestCase?

Or you want to keep testVariable as [AnyHashable: Any] then delete the structs and decode the JSON with traditional JSONSerialization

 
 
 
  
  //print(s) struct TestCase: Decodable { let content: Content } struct Content: Decodable { let message: [String: String] }
 
  

// ViewController.swift

private var testVariable = [AnyHashable:Any]()

private func loadJson(filename: String) {
    if let url = Bundle.main.url(forResource: filename, withExtension: "json") {
        do {
            let data = try Data(contentsOf: url)
            testVariable = try JSONSerialization.jsonObject(with: data) as? [AnyHashable: Any] ?? [:]

        } catch {
            print("JsonError: ", error)
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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