gpt4 book ai didi

JSONSerialization 返回错误,但 php 解析器

转载 作者:行者123 更新时间:2023-11-30 12:43:56 24 4
gpt4 key购买 nike

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

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com