2016-12-22 5 views
0

Ich habe eine Datatask erstellt, die eine JSON-Datei herunterlädt. Der JSON ist eine Reihe von Wörterbüchern. Dies ist ein Beispiel der Daten:Fehler Casting JSON Daten als [String: Beliebig]

[ 
    { 
    "userName": "Elon Musk", 
    "comment": "This is a fantastic Beer. I highly recommend it!" 
    }, 
    { 
    "userName": "SuperUser Account", 
    "comment": "I agree with Elon.. It rocks!" 
    } 
] 

Das Problem ist, ich nicht die json als [String: Any] werfen kann. Ich kann es nur auf [Any] werfen. Hier ist der relevante Code:

guard let json = try JSONSerialization.jsonObject(with: responseData, options: []) as? [String: Any] else { 
     print("error trying to convert data to JSON") 
     return 
    } 
    // now we have the json, let's just print it to prove we can access it 
    print("The json is: " + json.description) 

Guss als [Any] die json druckt gut. Gibt es noch etwas, schlägt die Besetzung fehl?

Gedanken bitte?

Edit .. Dies ist die url: http://www.smarttapp.com/DesktopModules/DnnSharp/DnnApiEndpoint/Api.ashx?method=GetCommentsFromArticleID&articleID=2240

+0

Sie haben selbst gesagt, es ist eine Reihe von Wörterbüchern, kein Wörterbuch . Daher können Sie es nicht in ein Wörterbuch umwandeln. Wolltest du es stattdessen auf "[[String: Any]]" übertragen? – Hamish

+0

OMG! .... @ Hamish. Ich kann nicht glauben, dass ich das vermisst habe! Ich werde heute Nacht schlafen können! Vielen Dank! –

Antwort

1

Ihr json ist array nicht Wörterbuch .. werfen es einfach [[String:Any]]

guard let json = try JSONSerialization.jsonObject(with: responseData, options: []) as? [[String: Any]] else { 
     print("error trying to convert data to JSON") 
     return 
    } 

    for dict in json { 
     print(dict["userName"]) 
    } 
+0

Kann jemand bitte erklären, warum ich drei down-Stimmen bekam, weil ich ein Stück Code nicht richtig eingerückt habe? –