2017-02-21 5 views
0

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

enter image description here

+0

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. –

Antwort

2

Sie haben JSON Antwort mit Top Ebene wie Array nicht dictionary. Sie müssen es also in [[String:Any]] anstelle von [String: Any] umwandeln.

Jetzt, wenn Sie diese Array Antwort auf Dictionary mit Typ [Int:Any] konvertieren möchten, dann müssen Sie das Array durchlaufen und Wörterbuch daraus machen.

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 {} 
+0

Ich habe folgende Meldung erhalten: 'Erwarteter Elementtyp 'für' as? [] ' –

+0

@S.M_Emamian Bearbeiten Sie Ihre Frage mit Ihrem aktuellen Versuch und zeigen Sie auch, wo Sie diesen Fehler erhalten. –

+0

meine Frage aktualisiert. –

0

Zuerst müssen Sie Ihre JSON String zu NSData konvertieren, indem die folgende

NSData *data = [jsonString dataUsingEncoding:NSUTF8StringEncoding]; 

tun dann einfach die JSONObjectWithData Methode verwenden, es Objekt JSON zu konvertieren

id json = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil]; 
+0

@KrishnaCA nichts falsch mit meiner Antwort, der Rückgabetyp in meinem Fall ist eine ID. Die JSON-Antwort des Fragestellers ist ein Dictionary-Array. Also sollte der Fragesteller ihn entweder auf "[AnyObject]" werfen oder wenn er versucht objective-c zu verwenden 'id' –

+0

Bitte fügen Sie die Erklärung in die Antwort ein. – KrishnaCA

0

Ich würde SwiftyJSON empfehlen, was es einfach macht, mit JSON-Daten in Swift zu konvertieren und darauf zuzugreifen.

// 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

-1
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) 
Verwandte Themen