2016-09-15 6 views
0

Je veux analyser ce JSON, au plus haut niveau JSON entrant est un tableau, comment accéder aux informations du dictionnaire dans le tableau?JSON Structure pour analyser les données JSON

[ 
     { 
     "id": 1, 
     "name": "Leanne Graham", 
     "username": "Bret", 
     "email": "[email protected]", 
     "address": { 
      "street": "Kulas Light", 
      "suite": "Apt. 556", 
      "city": "Gwenborough", 
      "zipcode": "92998-3874", 
      "geo": { 
      "lat": "-37.3159", 
      "lng": "81.1496" 
      } 
     }, 
     "phone": "1-770-736-8031 x56442", 
     "website": "hildegard.org", 
     "company": { 
      "name": "Romaguera-Crona", 
      "catchPhrase": "Multi-layered client-server neural-net", 
      "bs": "harness real-time e-markets" 
     } 
     } 
] 

c'est mon code mais je ne sais pas comment détecter les données du dictionnaire.

func profileFromJSONData(data : NSData) -> ProfileResult { 

     do{ 
      let jsonObject : [[String:AnyObject]] 
      = try NSJSONSerialization.JSONObjectWithData(data, options: []) as! [[String:AnyObject]] 

      for profileJSON in jsonObject { 
       if let profile = profileFromJsonObject(profileJSON) { 
        finalProfile.append(profile) 
       } 
      } 
      return .Success(finalProfile) 
     } 
     catch let error { 
      return .Failure(error) 
     } 

    } 

est ma méthode de profileFromJsonObject pour JSON analyse syntaxique en instance de profil

func profileFromJsonObject(json: [String:AnyObject]) -> UserProfile?{ 

     guard let 
      id = json["id"] as? Int, 
      name = json["name"] as? String, 
      userName = json["username"] as? String, 
      email = json["email"] as? String, 
      address = json["address"] as? NSDictionary, 
      phone = json["phone"] as? String, 
      website = json["website"] as? String, 
      company = json["company"] as? NSDictionary 
      else { 
       return nil 
     } 

    let obj = UserProfile(id: id, name: name, userName: userName, email: email, address: address, phone: phone, website: website, company: company) 
     return obj 
    } 
+0

Je suis appel fonction profileFromJsonObject pas profileFromJSONData. – ava

+0

dans la fonction profileFromJsonObject J'analyse json array dans une instance de profil. – ava

+0

Afficher la méthode 'profileFromJsonObject'. –

Répondre

1

J'ai essayé votre JSON en le prenant dans le fichier local, et je suis capable d'analyser à l'objet modèle de la manière suivante. Vous venez de mettre votre JSON à distance dans mon code, je l'espère travailler

func getTheLocalJSON() 
{ 
    let filePath = NSBundle.mainBundle().pathForResource("test", ofType: "json"); 
    let data = NSData.init(contentsOfFile: filePath!); 

    var json : NSArray! 
    do{ 
     json = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.AllowFragments) as! NSArray; 
    }catch{ 

    } 

    print("json \(json)"); 

    let dictResponse = json.objectAtIndex(0) as! NSDictionary; 

    let objUser = profileFromJsonObject(dictResponse)! as UserProfile; 

    print("user : \(objUser)"); 

    //Code to access company name and show it as screen title 
    self.title = (objUser.company)!["name"] as? String; 

    lblCompanyname.text = (objUser.company)!["name"] as? String; 
    lblCatchPhrase.text = (objUser.company)!["catchPhrase"] as? String; 
    lblbs.text = (objUser.company)!["bs"] as? String; 

} 

func profileFromJsonObject(json: NSDictionary) -> UserProfile?{ 

    guard let 
     id = json["id"] as? Int, 
     name = json["name"] as? String, 
     userName = json["username"] as? String, 
     email = json["email"] as? String, 
     address = json["address"] as? NSDictionary, 
     phone = json["phone"] as? String, 
     website = json["website"] as? String, 
     company = json["company"] as? NSDictionary 
     else { 
      return nil 
    } 

    let obj = UserProfile(id: id, name: name, userName: userName, email: email, address: address, phone: phone, website: website, company: company) 

    return obj 
} 

Sortie:

enter image description here

+0

cela fonctionne bien, mais comment accéder à l'adresse ou le dictionnaire de la société pour afficher ce détail dans la vue détaillée? – ava

+0

Vous pouvez utiliser comme ceci pour accéder au dictionnaire: print ("nom de l'entreprise: \ ((objUser.company)! [" Nom "])"); – Janmenjaya

+0

Oui c'est le moyen idéal pour accéder aux données du dictionnaire, et résoudre mon problème. – ava