2017-05-07 127 views
-5

好吧,我有這個服務器響應:如何從JSON數組中獲取字符串數組?

{ 
cars =  (
{ 
"color" = red; 
"model" = ferrari; 
"othersAtributes" = others atributes; 
},{ 
"color" = blue; 
"model" = honda; 
"othersAtributes" = others atributes; 
},{ 
"color" = green; 
"model" = ford; 
"othersAtributes" = others atributes; 
},{ 
"color" = yellow; 
"model" = porshe; 
"othersAtributes" = others atributes; 
} 
) 
} 

我需要汽車模型的列表。一系列車型,設置爲一個列表。

回答

0

首先你需要從服務器的原始響應轉換成斯威夫特Dictionary串。

let payload = [ 
    "cars": [ 
    [ 
     "color": "red", 
     "model": "ferrari", 
     "othersAtributes": "others atributes" 
    ], 
    [ 
     "color": "blue", 
     "model": "honda", 
     "othersAtributes": "others atributes" 
    ], 
    [ 
     "color": "green", 
     "model": "ford", 
     "othersAtributes": "others atributes" 
    ], 
    [ 
     "color": "yellow", 
     "model": "porshe", 
     "othersAtributes": "others atributes" 
    ] 
    ] 
] 

然後

let models: [String] = payload["cars"]!.map({ $0["model"] as! String }) 
print(models) 

會給你["ferrari", "honda", "ford", "porshe"]

(您可能想更換力量解開!與安全的錯誤處理機制。)

+0

我該如何轉換?喜歡這個? '讓有效載荷=響應爲? [字符串:任何]'? – steibour

+0

我假設服務器有效載荷是標準的JSON格式,並且您使用'NSURLSessionDataTask'來請求它,以便獲得一個'Data'對象。那麼答案將是@Vignesh J發佈的內容。儘管我建議使用'[String:Any]'來更快速地使用Swift-y。 'let payload:[String:Any] = NSJSONSerialization.JSONObjectWithData(data,options:NSJSONReadingOptions.MutableContainers,error:nil)as! [String:Any]' – xiangxin

+0

我用alamofire – steibour

0

試試這個片段。沒有完美測試。我猜測汽車是一個數組:

var modelsArray = [String]() 
     for index in cars.enumerated(){ 
      let model = cars[index].value(forKey: "model") 
      modelsArray.append(model) 
     } 
-1

此代碼爲得到JSON數組

func searchFunction(searchQuery: NSString) { 
     var url : NSURL = NSURL.URLWithString(" ENTER YOUR URL") 
     var request: NSURLRequest = NSURLRequest(URL:url) 
     let config = NSURLSessionConfiguration.defaultSessionConfiguration() 
     let session = NSURLSession(configuration: config) 

     let task : NSURLSessionDataTask = session.dataTaskWithRequest(request, completionHandler: {(data, response, error) in 

      var newdata : NSDictionary = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: nil) as NSDictionary 

      var info : NSArray = newdata.valueForKey("cars") as NSArray 

      var color: String? = info.valueForKey("color") as? String 
      println(color) 


      var model: NSString = info.valueForKey("model") as NSString //Crashes 
      println(model) 

    var othersAtributes: NSString = info.valueForKey("othersAtributes") as NSString //Crashes 
      println(othersAtributes) 

      }); 


     task.resume() 


    } 
+0

參考鏈接:http://stackoverflow.com/questions/24074042/getting-values-from-json-array -in-swift –

相關問題