将解密的字符串转换为 JSON 对象

Convert decrypted string into JSON object

解密来自 API 的回复后,我得到一个字符串 "name:DM100, profile:[1,2,4,5]"

我如何将其转换为 json 对象,其中名称是字符串,配置文件是数组

我试过使用但没有得到

if let data = testString.data(using: .utf8) {
        do {
            return try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any]
        } catch {
            print("JSON Serialization Error :-> \(error.localizedDescription)")
        }
    }
    return nil
}

您可以使用以下代码获取输出:

但字符串必须首先具有有效的JSON格式,如下所示:

 let string = "{\"name\":\"DM100\", \"profile\":[1,2,4,5]}"
            let data = string.data(using: .utf8)!
            do {
                if let jsonObj = try JSONSerialization.jsonObject(with: data, options : .allowFragments) as? Dictionary<String,Any> {
                    print(jsonObj)
                } else {
                    print("JSON Error")
                }
            } catch let error as NSError {
                print(error)
            }

您的 JSON 字符串无效。它应该是这样的:

let testString = "{\"name\":\"DM100\", \"profile\":[1,2,4,5]}"

if let data = testString.data(using: .utf8) {
    do {
        if let json = try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any] {
            print(json["name"])
        }
    }
    catch {
        print(error.localizedDescription)

    }
}

以大括号开始和结束 {} 并用双引号将字符串键和值括起来。