2017-05-07 126 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 –

相关问题