JSONSerialization 返回错误,但 php 解析器

标签 json swift serialization swift3 jsonserializer

我从服务器收到一个 JSON 字符串,它看起来像这样:

[[{\"type\":\"action\",\"action\":\"courier_on_map\",\"text\":\"\\u0421\\u043c\\u043e\\u0442\\u0440\\u0435\\u0442\\u044c \\u043d\\u0430 \\u043a\\u0430\\u0440\\u0442\\u0435\"}]]

Web 解析器显示“JSON 字符串有效,但 JSON 数据不准确”。然而 JSONSerialization 说:

字符 1 周围的对象中的值没有字符串键

并返回错误。

代码:

    func convertToNSDictionary() -> NSDictionary?
    {
        var string = self
        string = string.replacingOccurrences(of: "[", with: "")
        string = string.replacingOccurrences(of: "]", with: "")

        if let data = string.data(using: .utf8) {
            do {
                return try JSONSerialization.jsonObject(with: data, options: []) as? NSDictionary
            } catch {
                print(error.localizedDescription)
            }
        }

        return nil
    }

最佳答案

不要手动操作原始 JSON 字符串。

假设您的代码位于 String 的扩展内,则:

let str = "[[{\"type\":\"action\",\"action\":\"courier_on_map\",\"text\":\"\\u0421\\u043c\\u043e\\u0442\\u0440\\u0435\\u0442\\u044c \\u043d\\u0430 \\u043a\\u0430\\u0440\\u0442\\u0435\"}]]"

extension String {
    func convertToDictionary() -> [String:Any]? {
        let str = self

        guard let data = str.data(using: .utf8),
              let json = try? JSONSerialization.jsonObject(with: data, options: []) as! [[[String:Any]]]
        else {
            return nil
        }

        //debug prints
        print(json)
        let innerArray = json.first!
        print(innerArray)
        let dict = innerArray.first!
        print(dict)
        if let type = dict["type"] {
            print(type)
        }
        //

        return dict
    }
}

let dict = str.convertToDictionary()

print(dict)

打印:

[[["type": action, "action": courier_on_map, "text": Смотреть на карте]]]
[["type": action, "action": courier_on_map, "text": Смотреть на карте]]
["type": action, "action": courier_on_map, "text": Смотреть на карте]
action
Optional(["type": action, "action": courier_on_map, "text": Смотреть на карте])

如果你确实需要一个NSObject,你可以强制转换它:

let nsDict = dict! as NSDictionary

关于JSONSerialization 返回错误,但 php 解析器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41892458/

相关文章:

json - Composer-> 不包含有效的 JSON

java - 解决 java.util.ArrayList$SubList notSerializable 异常

json - 使用 Azure Web 作业将数据导入到 Azure SQL

javascript - 获取所有图像大小的 flickr api

swift - Swift 2 和 Swift 3 中的核心数据 momd 扩展

swift - 二元运算符 '/' 不能应用于两个 'T' 操作数

ios - 具有多个路径的UIBezierPath不连接具有斜角类型的线

java - 如何将嵌套 JSON 映射到简单对象?

c# - 如何在 Azure Functions 中使用 IAsyncCollector 和 System.Text.Json 设置驼峰式大小写?

javascript - 从 JSON 形成构造函数