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

时间:2019-05-24 04:56:01

标签: ios swift4.2

解密来自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
}

2 个答案:

答案 0 :(得分:0)

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

但是String必须首先具有有效的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)
            }

答案 1 :(得分:0)

您的JSON字符串无效。它应该看起来像这样:

BiFunction

以大括号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) } } 开始和结束,并在字符串键和值两边加上双引号。