2017-05-07 28 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

JSON配列から文字列を取得ファーストため。

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

私はどのように変換できますか?このような? 'ペイロード=レスポンスとしましょう? [String:Any] '? – steibour

+0

サーバのペイロードは標準のJSON形式であり、 'NSURLSessionDataTask'を使ってリクエストしているので、' Data'オブジェクトを取得します。答えは@Vignesh Jが投稿したものです。 Swift-yをもっと使うには、 '[String:Any]'を使うことをお勧めします。 'let payload:[String:Any] = NSJSONSerialization.JSONObjectWithData(データ、オプション:NSJSONReadingOptions.MutableContainers、エラー:なし)! '文字列: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

このコードは、サーバーからスウィフトDictionaryに生の応答を変換するために必要なすべての

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 –

関連する問題