2017-02-13 6 views
2

여기 URL을 통해 JSON을 구문 분석하려고합니다. 실제 JSON 데이터를 URL에서 사용할 수 있습니다. 그래서 그것을 구문 분석하고 내 응용 프로그램에서 Alamofire를 사용하여 읽을 필요가있다. 그러나 나는 그것을 할 수 없다.Swift 3.0에서 Alamofire를 사용하여 타사 라이브러리없이 JSON을 구문 분석하는 방법

JSON 내 데이터입니다.

{ 
     "main": [ 
     { 
     "date": "2017-01-11", 
     "USDARS": "15.8302", 
     "USDCLP": "670.400024", 
     "USDSDG": "6.407695" 
     }, 
     { 
     "date": "2017-01-12", 
     "USDARS": "15.804999", 
     "USDCLP": "661.599976", 
     "USDSDG": "6.407697" 
     }, 
     { 
     "date": "2017-01-13", 
     "USDARS": "15.839041", 
     "USDCLP": "659.200012", 
     "USDSDG": "6.407704" 
     }, 
     { 
     "date": "2017-01-14", 
     "USDARS": "15.839041", 
     "USDCLP": "659.200012", 
     "USDSDG": "6.407704" 
     } 
    ] 
} 

은 어떻게 실제로 내가 URL을 통해 JSON 데이터 위의 구문 분석하는 것을 시도하고있다 아래

빠른 3.0 Alamofire을 사용하여 읽을 않습니다.

Alamofire.request("myurl") .responseJSON { response in 

      print("In Alamofire") 
      if let arr = response.result.value as? [String:AnyObject] 
      { 

       if let arr = response.result.value as? [NSDictionary] 
       { 
        let val1 = (arr["main"]["USDARS"] as? String) 
        print(val1) 
        //It does not print any thing. 
       } 
      } 
     } 

도와주세요. 나는 그것에 익숙하지 않다.

+0

arr [ "main"] [0] [ "USDARS"], "main"은 객체의 배열입니다. – JuicyFruit

+0

며칠 전에 같은 질문을 게시하지 않으셨습니까? 이전 주석이나 질문에 따라 코드를 변경 한 사실을 기억하지 못합니다. 나는 이전에 다음과 같이보고했다. 왜'arr = response.result.value를? [문자열 : AnyObject]'then'arr = response.result.value as if? [NSDictionary]'이치에 맞지 않습니다. NSStuff에 Swift Type을 선호해야합니다. – Larme

답변

7

최고 수준의 JSON은 [String:Any]이며, 주요 매우 유용 Alamofire

귀하의 경우에는 당신이 할 수있는 JSON 구문 분석을위한 라이브러리입니다 당신은 SwiftyJson를 사용해야합니다 [[String:String]]

Alamofire.request("myurl") .responseJSON { response in 
     if let result = response.result.value as? [String:Any], 
      let main = result["main"] as? [[String:String]]{ 
      // main[0]["USDARS"] or use main.first?["USDARS"] for first index or loop through array 
      for obj in main{ 
       print(obj["USDARS"]) 
       print(obj["date"]) 
      } 
     } 
    } 
+0

예 'USDARS'의 모든 값을 인쇄하지만 'obj'의 특정 값이나 마지막 값만 인쇄하는 방법 –

+0

처음에는 'main.first? [ "USDARS"]'.. 또는 얻을 수 있습니다. 'main [0] [ "USDARS"]' –

+0

와 같은 색인. 특정 날짜에 대한 가치를 얻고 싶다면 어떻게해야합니까? –

0

즉 배열입니다 swiftyJson이 같은 :

//Array & Dictionary 
var jsonArray: JSON = [ 
    "main": ["date": "2017-01-11", "USDARS": "15.8302"] 
] 

let dateString = jsonArray["main"][0]["date"].string 

print(dateString) = "2017-01-11" 
0
@IBAction func btnget(_ sender: UIButton) { 

    let urlpath : String = "http://202.131.123.211/UdgamApi_v4/App_Services/UdgamService.asmx/GetAllTeacherData?StudentId=2011111" 

    let url = URL(string: urlpath) 

    var urlrequest = URLRequest(url: url!) 

    urlrequest.httpMethod = "GET" 

    let config = URLSessionConfiguration.default 
    let session = URLSession(configuration: config) 

    let task = session.dataTask(with: urlrequest) { (data, response, error) in 

     do { 
      guard let getResponseDic = try JSONSerialization.jsonObject(with: data!, options: []) as? [String: AnyObject] else { 
       print("error trying to convert data to JSON") 
       return 
      } 
      // now we have the todo, let's just print it to prove we can access it 

      print(getResponseDic as NSDictionary) 

      let dic = getResponseDic as NSDictionary 
      let msg = dic.object(forKey: "message") 

      print(dic) 
      //let arrObj = dic.object(forKey: "teacherDetail") as! NSArray 
      //print(arrObj) 

      //let arr = dic.value(forKey: "TeacherName")as! NSArray 

      print(((dic.value(forKey: "teacherDetail") as! NSArray).object(at: 0) as! NSDictionary).value(forKey: "TeacherName") as! String) 

      // the todo object is a dictionary 
      // so we just access the title using the "title" key 
      // so check for a title and print it if we have one 

      // print("The title is: " + todoTitle) 
     } catch { 
      print("error trying to convert data to JSON") 
      return 
     } 
    } task.resume() 
} 
+0

입니다. 코드 만 대답하면 장래의 독자들에게 많은 정보를 제공하지 않으므로 권장하지 않습니다. 작성한 것에 대해 설명해주십시오. – WhatsThePoint

관련 문제