如何在iOS Swift 3中将JSON字符串转换为字典数组
我有这根绳子如何在iOS Swift 3中将JSON字符串转换为字典数组,ios,json,swift,Ios,Json,Swift,我有这根绳子 [{\"label\":\"Issue Name\",\"value\":\"my dirst iOS \",\"_id\":\"issueName\"},{\"label\":\"Issue DueDate\",\"value\":\"15-12-2016\",\"_id\":\"dueDate\"}] 例如,我想将其转换为类型[NSDictionary] [ { "label": "Issue Name", "value": "my dirst iOS "
[{\"label\":\"Issue Name\",\"value\":\"my dirst iOS \",\"_id\":\"issueName\"},{\"label\":\"Issue DueDate\",\"value\":\"15-12-2016\",\"_id\":\"dueDate\"}]
例如,我想将其转换为类型[NSDictionary]
[
{
"label": "Issue Name",
"value": "my dirst iOS ",
"_id": "issueName"
},
{
"label": "Issue DueDate",
"value": "15-12-2016",
"_id": "dueDate"
}
]
有人能告诉我怎么做吗。我已经尝试过首先尝试删除斜杠
stringJson.stringByReplacingOccurrencesOfString("\\", withString: "")
然后用JsonConverter转换它
func convertToDictionary(text: String) -> Any? {
if let data = text.data(using: .utf8) {
do {
return try JSONSerialization.jsonObject(with: data, options: []) as? Any
} catch {
print(error.localizedDescription)
}
}
return nil
}
然后
首先,尝试删除斜线
stringJson.stringByReplacingOccurrencesOfString("\\", withString: "")
然后用JsonConverter转换它
func convertToDictionary(text: String) -> Any? {
if let data = text.data(using: .utf8) {
do {
return try JSONSerialization.jsonObject(with: data, options: []) as? Any
} catch {
print(error.localizedDescription)
}
}
return nil
}
然后
捷径5捷径
//MARK:- Calling
if let list = self.convertToDictionary(text: stringJson) as? [AnyObject] {
print(list);
}
//MARK:- Remove the Slashes
let text = stringJson.replacingOccurrences(of: "\\", with: "")
//MARK:- Convert it with JsonConverter
func convertToDictionary(text: String) -> Any? {
if let data = text.data(using: .utf8) {
do {
return try JSONSerialization.jsonObject(with: data, options: []) as? Any
} catch {
print(error.localizedDescription)
}
}
return nil
}Swift 5简易方法
//MARK:- Calling
if let list = self.convertToDictionary(text: stringJson) as? [AnyObject] {
print(list);
}
//MARK:- Remove the Slashes
let text = stringJson.replacingOccurrences(of: "\\", with: "")
//MARK:- Convert it with JsonConverter
func convertToDictionary(text: String) -> Any? {
if let data = text.data(using: .utf8) {
do {
return try JSONSerialization.jsonObject(with: data, options: []) as? Any
} catch {
print(error.localizedDescription)
}
}
return nil
}可能重复的内容确实描述了如何在Swift 1、2和3中解析JSON。您能解释一下为什么已经回答的问题没有帮助吗?您收到错误消息了吗?服务器团队应该删除每个键和值之前的斜杠,然后使用jsonserialization进行解析,在我使用建议的代码时解决您的问题。它给我的是nil@volker可能的重复,它确实描述了如何在Swift 1、2和3中解析JSON,你能解释一下为什么已经回答的问题没有帮助吗?您收到错误消息了吗?服务器团队应该删除每个键和值之前的斜杠,然后使用jsonserialization进行解析,在我使用建议的代码时解决您的问题。它给了我零@Volkerlight。但是请注意,hatim您的最高级别是json数组,因此请先将其去掉。在这种情况下,返回any将显示返回“any”时的错误,因为“jsonResult生成”any“不是预期的上下文结果类型”[String:any]“对不起,我的错,我的代码中犯了一个错误,在您编辑之前,我无法对答案进行投票,请做一个编辑,这样我就可以打开voteRight了。但是请注意,hatim您的最高级别是json数组,因此请先将其去掉。在这种情况下,返回any将显示返回“any”时的错误,因为“jsonResult生成”any“不是预期的上下文结果类型”[String:any]“对不起,我的错,我的代码中犯了一个错误,在您编辑之前,我无法对答案进行投票,请编辑一下,这样我就可以投票了