0

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?

5
  • 2
    Possible duplicate of How to convert a JSON string to a dictionary? Commented Dec 15, 2016 at 11:28
  • 1
    This does exactly describe how to parse JSON in Swift 1, 2 and 3 Commented Dec 15, 2016 at 11:28
  • 1
    can you explain why the already answered question did not help? Did you get error messages? Commented Dec 15, 2016 at 11:29
  • server team should remove slash before each key and value and then by parsing with jsonserialization solve your issue Commented Dec 15, 2016 at 11:39
  • When i am using suggested code. it is giving me nil @Volker Commented Dec 15, 2016 at 11:41

2 Answers 2

4

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);
    }
Sign up to request clarification or add additional context in comments.

4 Comments

Right. But note hatim your highest level is a json ARRAY, so take that out first.
returning any in this case
Its showing error on returning "ANY" as "jsonResult produce "Any" not the expected contextual result type"[String: Any]""
Sorry my bad, i made a mistake in my code, I am not able to up vote the answer till u edit, please make an edit so that i can up vote
2

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

}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.