2016-08-10 3 views
0

작은 애플리케이션을 가지고 있고 버튼 중 하나에서 온라인으로 JSON 파일을 검색하여 결과를 인쇄하지만 인쇄 할 필요없이 JSON 결과를 어떻게 활용할 수 있습니까? 전체 JSON을 인쇄하려면 JSON [ "data"] [1]과 같은 값 중 하나만 인쇄하고 싶습니다.신속한 특정 JSON 값 얻기

@IBAction func approveuser(sender: AnyObject) { 
     let postEndpoint: String = "https://example.com/example.json" 
     let url = NSURL(string: postEndpoint)! 
     let session = NSURLSession.sharedSession() 
     let postParams : [String: AnyObject] = ["UUID": UIDevice.currentDevice().identifierForVendor!.UUIDString, "requested": place] 
     let request = NSMutableURLRequest(URL: url) 
     request.HTTPMethod = "POST" //can be changed. 
     request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type") 
     do { 
      request.HTTPBody = try NSJSONSerialization.dataWithJSONObject(postParams, options: NSJSONWritingOptions()) 
      print(postParams) 
     } catch { 
      print("bad things happened") 
     } 
     session.dataTaskWithRequest(request, completionHandler: { (data: NSData?, response: NSURLResponse?, error: NSError?) -> Void in 
      guard let realResponse = response as? NSHTTPURLResponse where 
       realResponse.statusCode == 200 else { 
        print("Not a 200 response") 
        return 
      } 



      // Read the JSON 
      if let postString = NSString(data:data!, encoding: NSUTF8StringEncoding) as? String { 
       print("POST: " + postString) 
       // 
      } 
     }).resume() 

    } 

답변

0

JSON 값이 자신의 키를 통해 검색됩니다

여기 내 코드입니다. 배열이든 객체이든 상관 없습니다. json은 여러 개의 다른 json 객체 또는 json 배열을 포함 할 수 있습니다. 고유 한 사용자 정의 클래스를 사용하여 값을 검색 할 수 있습니다. 이를 구현하려면 code을 이해하면 이해할 수 있습니다.
또는 iOS에서 SwiftyJSON을 사용하여 더 적은 브레인 스토밍으로 값을 검색 할 수 있습니다. 'dataFromNetworking는'당신을 NSData입니다

let json = JSON(data: dataFromNetworking) 
if let userName = json[0]["user"]["name"].string { 
    //Now you got your value 
} 

이 URL에서 읽고 위와 같이 JSON을 포함 : 당신이 코딩 할 수 있습니다이를 위해

{ {"user": { 
     "name": "..." 
     } 
    }, 
    {"address": "..." 
    } 
} 

-로 SwiftyJSON를 사용하여 예를 들어, 당신은 할 수 있습니다.

이렇게하면 json에서 값을 검색 할 수 있습니다. SwiftyJSON에 대한 자세한 내용을 보려면 link으로 이동하십시오. 여기

+0

이 나에게의 오류 '사용을 줄 미확인 된 해결사 "JSON" ' – Matt

+0

포드가 포함되어 있습니까? 당신이 코코아포드 또는 carthage를 사용하여 SwiftyJSON을 통합하지 않을 때까지 작동하지 않습니다. –

0

당신은 JSON에서 데이터를 불러 오는 예를 :

JSON 형식 :

[ 
    { 
    "person": { 
     "name": "Rob", 
     "age": "4" 
    } 
    }, 
    { 
    "person": { 
     "name": "joe", 
     "age": "73" 
    } 
    } 
] 

관련 코드 :이 코드를하려고하면

var json: Array!  
do { 
     json = try NSJSONSerialization.JSONObjectWithData(JSONData, options: NSJSONReadingOptions()) as? Array 
    } catch { 
     print(error) 
    } 

    if let item = json[0] as? [String: AnyObject] { 
     if let person = item["person"] as? [String: AnyObject] { 
     if let age = person["age"] as? Int { 
      print("Rob's age is \(age)") 
     } 
     } 
    }