2017-03-17 6 views
-2

tableau je reçois JSON comme celui-ci à partir du serveur:JSON conversion rapide à

array('id' => '1', 'name' => 'Radni nalog 1', 'threadTypeList' => array(
      array('id' => '1', 'name' => 'Crvena'), 
      array('id' => '2', 'name' => 'Plava'), 
      array('id' => '3', 'name' => 'Zelena'), 
      array('id' => '4', 'name' => 'Žuta'), 
     ), 'token' => 'xxuoE73VKwyKk1KmGTy26P72cgsuneMzNOes'); 

Comment puis-je convertir ce JSON au dictionnaire. Voici ma fonction de conversion, mais c'est totalement faux et je suis coincé avec.

func convertStringToDictionary2(text: String) -> [AnyObject]? { 
    if let data = text.dataUsingEncoding(NSUTF8StringEncoding) { 
     do { 
      let json = try NSJSONSerialization.JSONObjectWithData(data, options: .MutableContainers) as? [AnyObject] 
      return json 
     } catch { 
      print("Something went wrong") 
     } 
    } 
    return nil 
} 

et lorsque je tente d'obtenir des données comme ceci:

let result = convertStringToDictionary(jsonString as String) 

//creating array of objects threadType and populating threadTypeList property 
let resultThreadList = (result?["threadTypeList"] as! String) 

let new = convertStringToDictionary2(resultThreadList as String) 

Je reçois une erreur: Impossible jeter la valeur de type '__NSArrayI' (0x10f20dd88) à 'NSString' (0x10df90c40).

Je suis capable d'obtenir toutes les variables de json sauf ** threadTypeList ** qui est un tableau de tableaux.

+0

pourquoi convertissez-vous resultThreadList en tant que chaîne? –

Répondre

0

L'erreur

Could not cast value of type '__NSArrayI' (0x10f20dd88) to 'NSString' (0x10df90c40)

signifie:

L'objet que vous allez l'accès est Array mais vous voulez obtenir un String ce qui est impossible.

let resultThreadList = result?["threadTypeList"] as! [[String:AnyObject]] 

resultThreadList implique un tableau, ainsi que le type PHP 'threadTypeList' => array( mais considèrent qu'un tableau PHP (associatif) array('id' => '1' est en fait un dictionnaire.