-1

I have a json like this :

[
  {
    "id" : 887,
    "title" : "ماه نو",
    "voice_actor" : "ع. پاشایی",
    "compiler" : "رابیندرانات تاگور",
    "cover_image" : "d5c446a1d81340d2bb912d51b00a3d79"
  },
  {
    "id" : 607,
    "title" : "حکایت آن که دلسرد نشد (درس هایی برای رسیدن به موفقیت و ثروت)",
    "voice_actor" : "حمید محمدی",
    "compiler" : "مارک فیشر",
    "cover_image" : "26ead648b33e4977805c7e979f8cc78c"
  }
]

now I would like to convert it to a dictionary like this :

key:value

in this case the key is arbitrary (an unique Int) and value is objects.

I wanted to use this function but it returns nil :

 func convertToDictionary(text: String) -> [String: Any]? {
        if let data = text.data(using: .utf8) {
            do {
                return try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any]
            } catch {
                print(error.localizedDescription)
            }
        }    

 let value = self.convertToDictionary(text: abovejson)
 //value is null

updated

I want to use @Nirav D answer but I got an error :

   func convertToDictionary(text: String) -> [String: Any]? {
        if let data = text.data(using: .utf8) {
            do {
                let array = try JSONSerialization.jsonObject(with: data, options: []) as? [[String: Any]] as? []
                var dictionary = [Int:Any]()
                //Loop through array and set object in dictionary
                for (index,item) in array.enumerated() {
                    let uniqueID = index //Or generate uniqued Int id
                    dictionary[uniqueID] = item
                }
            }
            catch {}
        }
        return nil
    }


Expected element type for as? []

enter image description here

S.M_Emamian
  • 17,005
  • 37
  • 135
  • 254
  • you can create a model class of your data.Then parse your json and get your values and pass them to model object and append in array. – Tushar Sharma Feb 21 '17 at 09:05

4 Answers4

2

You have JSON response with Top level as Array not dictionary. So you need to cast it to [[String:Any]] instead of [String: Any].

Now if you want to convert this Array response to Dictionary with type [Int:Any] then you need to loop through the array and make dictionary from it.

do {
     let array = try JSONSerialization.jsonObject(with: data, options: []) as? [[String: Any]] ?? []
     var dictionary = [Int:Any]()
     //Loop through array and set object in dictionary
     for (index,item) in array.enumerated() {
         let uniqueID = index //Or generate uniqued Int id 
         dictionary[uniqueID] = item
     }
}
catch {}
Nirav D
  • 71,513
  • 12
  • 161
  • 183
0

First you will need to convert your JSON String to NSData by doing the following

NSData *data = [jsonString dataUsingEncoding:NSUTF8StringEncoding];

then simply use the JSONObjectWithData method to convert it to JSON object

id json = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
  • @KrishnaCA nothing wrong with my answer, the return type in my case is an id. The asker json response is an array of dictionary. So the asker should either cast it to `[AnyObject]` or if he's intending to try objective-c use `id` –  Oct 26 '17 at 16:43
  • Please include the explanation in the answer. – KrishnaCA Oct 27 '17 at 06:08
0

I would recommend using SwiftyJSON which makes it easy to convert and access with JSON data in Swift.

// A Simple sample
let json = JSON(data: dataFromNetworking)
if let userName = json[0]["user"]["name"].string {
  //Now you got your value
}

https://github.com/SwiftyJSON/SwiftyJSON

XY L
  • 25,431
  • 14
  • 84
  • 143
-2
func convertToDictionary(text: String) -> [String: Any]? {
if let data = text.data(using: .utf8) {
    do {
        return try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any]
    } catch {
        print(error.localizedDescription)
    }
}
return nil

}

let str = "{\"name\":\"James\"}"

let dict = convertToDictionary(text: str)

swift 2

func convertStringToDictionary(text: String) -> [String:AnyObject]? {
if let data = text.dataUsingEncoding(NSUTF8StringEncoding) {
    do {
        return try NSJSONSerialization.JSONObjectWithData(data, options: []) as? [String:AnyObject]
    } catch let error as NSError {
        print(error)
    }
}
return nil
 }

 let str = "{\"name\":\"James\"}"

  let result = convertStringToDictionary(str)