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? []