如何将字符串转换为json字典。?

问题描述 投票:0回答:1

下面的代码我正在将字符串转换为字典,但无法正常工作。

let body = "{status:0}"
    do {
            let dictionary = try convertToDictionary(from: body ?? "")
            print(dictionary) // prints: ["City": "Paris"]
        } catch {
            print(error)
        }

    func convertToDictionary(from text: String) throws -> [String: String] {

    guard let data = text.data(using: .utf8) else { return [:] }

    let anyResult: Any = try JSONSerialization.jsonObject(with: data, options: [])

    return anyResult as? [String: String] ?? [:]
}
ios swift nsstring
1个回答
0
投票

该值为Int,所以类型转换为[String:String]失败。

这与any值类型一起使用

let body = "{status:0}"
do {
    let dictionary = try convertToDictionary(from: body)
    print(dictionary) // prints: ["City": "Paris"]
} catch {
    print(error)
}

func convertToDictionary(from text: String) throws -> [String: Any] {
    let data = Data(text.utf8)
    return try JSONSerialization.jsonObject(with: data) as? [String:Any] ?? [:]
}
© www.soinside.com 2019 - 2024. All rights reserved.