【问题标题】:JSONSerialization returns an error, but php parcerJSONSerialization 返回错误,但是 php 解析器
【发布时间】:2017-06-13 01:05:44
【问题描述】:

我从服务器接收到一个 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
    }

【问题讨论】:

  • 你可以在你的项目中使用这个最好的库,这只是你的代码,也许可以解决你的问题:github.com/SwiftyJSON/SwiftyJSON
  • 你的代码对我来说运行良好,检查你的字符串不是可选的。

标签: json swift serialization swift3 jsonserializer


【解决方案1】:

不要手动操作原始 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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-03-26
    • 2019-07-16
    • 1970-01-01
    • 1970-01-01
    • 2022-07-14
    • 1970-01-01
    • 2015-09-28
    • 1970-01-01
    相关资源
    最近更新 更多