2017-11-16 5 views
-1

Ich habe folgende JSON-DateiAbrufen von JSON Elemente in Swift 3

{ 
    "events": [ 
       { 
       "date": "01/11/2017", 
       "name": [ 
         "Tulsi Vivah", 
         "Pradosh Vrat" 
         ], 
       "photo": [ 
         "photo_chaturthi", 
         "photo_ekadashi" 
         ] 
       }, 
       { 
       "date": "03/11/2017", 
       "name": [ 
         "Guru Nanak Jayanti" 
         ], 
       "photo": [ 
         "photo_chaturthi", 
         "photo_ekadashi" 
         ] 
       } 
       ] 
} 

Ich möchte diese analysieren und die Elemente in der objectArray im Code setzen unter:

struct Objects { 

     var sectionName : String! 
     var sectionObjects : [String]! 
     var sectionImages : [String]! 
    } 
    var objectArray = [Objects]() 

Ich habe folgenden Code geschrieben zum lesen der Datei:

if let file = Bundle.main.url(forResource: "EventsEnglish112017", withExtension: "json") { 
      let data = try Data(contentsOf: file) 
      let json = try JSONSerialization.jsonObject(with: data as Data, options: []) 

Meine Frage ist, wie kann ich „json“ typisierte die einzelne Elemente lesen Sie das abo füllen ve objectArray.

Danke!

+0

Es gibt mehrere Tools, die Sie verwenden können, es ist nicht notwendig, es von Hand zu tun - obwohl Sie können, wenn Sie möchten. Sehen Sie sich zum Beispiel [Object Mapper] (https://github.com/Hearst-DD/ObjectMapper) oder [SwiftyJSON] (https://github.com/SwiftyJSON/SwiftyJSON) an. – Losiowaty

+3

Deklarieren Sie Ihre structs-Eigenschaften nicht implizit unwrapped optionals, nur um herum zu schaffen, einen Initialisierer (den der Compiler automatisch für Strukturen tun kann). Aus dem Code in Ihrer Frage, sehe ich keinen Grund für eine der Eigenschaften implizit unverpackte Optionals überhaupt sein ... –

+0

Bearbeitet für swift 3. Probieren Sie es aus, es wird Ihnen auf jeden Fall helfen und mich informieren, wenn es immer noch Probleme gibt. Viel Glück –

Antwort

-1

Um

if let path = Bundle.main.path(forResource: "myJson", ofType: "json") { 
    do { 
      let data = try Data(contentsOf: URL(fileURLWithPath: path), options: .mappedIfSafe) 
      let jsonResult = try JSONSerialization.jsonObject(with: data, options: .mutableLeaves) 
      if let jsonResult = jsonResult as? Dictionary<String, AnyObject>, let eventsInfo = jsonResult["events"] as? [Any] { 
        // Here you will get your data in Array format. 
        // for e.g 
        // print(eventsInfo[0]["date"]) 
        // Just pass this eventsInfo (Array) into you Object model initializer and parse with the keys there. 
      } 
     } catch { 
      // handle error 
     } 
} 
+0

Warum 'Pfad (forResource..' und' URL (fileURLWithPath' obwohl es 'url (forResource..'? Warum' .mutableLeaves' gibt, obwohl das Ergebnis einer unveränderlichen Konstante zugewiesen wurde? Warum Casting 'eventsInfo' zum Dictionary) obwohl es ein Array ist Warum "AnyObject", obwohl der Typ eindeutig Werttyp ("Any") ist? Und Ihre Swift 3-Version ist eigentlich Swift 2. – vadian

+0

@vadian Edited sah seine JSON nicht ordnungsgemäß –

1

A JSON ist ein Wörterbuch von Typ-Daten aus JSON Datei abrufen [String:Any?]

(Swift 3)

if let path = NSBundle.mainBundle().pathForResource("myJson", ofType: "json") 
{ 
    if let jsonData = NSData(contentsOfFile: path, options: .DataReadingMappedIfSafe, error: nil) 
    { 
     if let jsonResult = NSJSONSerialization.JSONObjectWithData(jsonData, options: NSJSONReadingOptions.MutableContainers, error: nil) as? [String: Any] 
     { 
      if let eventsInfo = jsonResult["events"] as? [Any] 
      { 
       // Here you will get your data in Array format. 
       // for e.g 
       // print(eventsInfo[0]["date"]) 
       // Just pass this eventsInfo (Array) into you Object model initializer and parse with the keys there. 
      } 
     } 
    } 
} 

(Swift 4) Um pa rse es:

if let dictionary = json as? [String: Any?] { 
    if let events = dictionary["events"] as? [[String: Any?]] { 

    // events is an array of JSON objects, so it's an array of dictionaries 
     for item in events 
     { 
      let date = item["date"] as? String // this is a String? 
      let name = item["name"] as? [String] 
      // same goes for 'photo' 
     } 
    } 
} 

Nun, da Sie die Daten abgerufen haben, können Sie es verwenden, um Ihre benutzerdefinierten Objekte costruct. Aber es ist besser, wenn Sie eine Bibliothek verwenden, die es für Sie macht, oder verwenden Sie Swift4