ich eine json wie diese muß Wörterbuch:Wie ein json von Objekten konvertieren
[
{
"id" : 887,
"title" : "ماه نو",
"voice_actor" : "ع. پاشایی",
"compiler" : "رابیندرانات تاگور",
"cover_image" : "d5c446a1d81340d2bb912d51b00a3d79"
},
{
"id" : 607,
"title" : "حکایت آن که دلسرد نشد (درس هایی برای رسیدن به موفقیت و ثروت)",
"voice_actor" : "حمید محمدی",
"compiler" : "مارک فیشر",
"cover_image" : "26ead648b33e4977805c7e979f8cc78c"
}
]
jetzt würde Ich mag es so zu einem Wörterbuch konvertieren:
key:value
in diesem Fall der key
ist beliebig (ein eindeutiger Int) und value
ist Objekte.
Ich wollte diese Funktion nutzen, aber es gibt 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
aktualisiert
I @Nirav D Antwort verwenden wollen, aber ich habe einen Fehler:
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? []
Sie können eine Modellklasse Ihrer Daten erstellen. Dann analysieren Sie Ihre JSON und holen Sie Ihre Werte und übergeben Sie sie an das Modellobjekt und anhängen im Array. –