Reputation: 218
I have this String
[{\"label\":\"Issue Name\",\"value\":\"my dirst iOS \",\"_id\":\"issueName\"},{\"label\":\"Issue DueDate\",\"value\":\"15-12-2016\",\"_id\":\"dueDate\"}]
I want to convert it to type [NSDictionary]
for example;
[
{
"label": "Issue Name",
"value": "my dirst iOS ",
"_id": "issueName"
},
{
"label": "Issue DueDate",
"value": "15-12-2016",
"_id": "dueDate"
}
]
Can someone tell me how to do that. I Have Already Tried How to convert a JSON string to a dictionary?
Upvotes: 0
Views: 5299
Reputation: 6021
Swift 5 Easy way
//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
}
Upvotes: 2
Reputation: 3580
first try to remove the slashes
stringJson.stringByReplacingOccurrencesOfString("\\", withString: "")
then 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
}
then
if let list = self.convertToDictionary(text: stringJson) as? [AnyObject] {
print(list);
}
Upvotes: 4