如何使用 SwiftyJSON 从我的 JSON 中获取选定的元素并将其打印在控制台上?
Posted
技术标签:
【中文标题】如何使用 SwiftyJSON 从我的 JSON 中获取选定的元素并将其打印在控制台上?【英文标题】:How can I get selected elements from my JSON using SwiftyJSON and print it on the console? 【发布时间】:2016-02-20 13:47:33 【问题描述】:我有一个以选定形式返回数据的网络服务:
["_id":"56c861d0bcb42e075f7d47bd",
"username":"Shaylee Thompson",
"photo":"photo.jpg",
"number":"one",
"description":"Aut officia et ipsam. Dolorem pariatur molestiae sed saepe voluptatem voluptatem. Non maiores doloribus quis eum reprehenderit fugit vitae.",
"__v":0,
"updated_at":"2016-02-20T12:53:36.931Z",
"created_at":"2016-02-20T12:53:36.922Z",
"location":
"type":"Point",
"coordinates":[-3.2880974020993934,49.8319259687921]
,
"_id":"55a9253297b21080ac8",
"username":"Eve Notter",
"photo":"photo.jpg",
"number":"two",
"description":"Aut officia et ipsam. Dolorem pariatur molestiae sed saepe voluptatem voluptatem. Non maiores doloribus quis eum reprehenderit fugit vitae.",
"__v":0,
"updated_at":"2016-02-20T12:53:36.931Z",
"created_at":"2016-02-20T12:53:36.922Z",
"location":
"type":"Point",
"coordinates":[-2.212142,41.14321231]
,
etc.
我想在我的控制台中显示上述每条记录中的location
、username
和description
。
我创建了一个名为 RestManager.swift
的类,其中包含两个方法:
static let sharedInstance = RestApiManager()
func getRandomUser(onCompletion: (JSON) -> Void)
let route = baseURL
makeHTTPGetRequest(route, onCompletion: json, err in
onCompletion(json as JSON)
)
func makeHTTPGetRequest(path: String, onCompletion: ServiceResponse)
let request = NSMutableURLRequest(URL: NSURL(string: path)!)
let session = NSURLSession.sharedSession()
let task = session.dataTaskWithRequest(request, completionHandler: data, response, error -> Void in
let json:JSON = JSON(data: data!)
onCompletion(json, error)
// if I put print(json) then I see the whole json in console
)
task.resume()
然后在不同的班级我写道:
override func viewDidLoad()
getDummyData()
func getDummyData()
RestApiManager.sharedInstance.getRandomUser json in
let results = json["username"]
for (index: String, subJson: JSON) in results
let user: AnyObject = JSON["username"].object
dispatch_async(dispatch_get_main_queue(),
print(user) //does not print anything so far
)
所以我的问题是 - 我应该如何修改我的 getDummyData
方法以便我可以在控制台中看到我的 JSON 元素?
【问题讨论】:
【参考方案1】:func getDummyData()
RestApiManager.sharedInstance.getRandomUser json in
for (index: String, subJson: JSON) in json
let user: AnyObject = subjson["username"].object
dispatch_async(dispatch_get_main_queue(),
print(user)
)
【讨论】:
以上是关于如何使用 SwiftyJSON 从我的 JSON 中获取选定的元素并将其打印在控制台上?的主要内容,如果未能解决你的问题,请参考以下文章
使用 SwiftyJSON(和 Alamofire)解析 JSON 值
如何使用 SwiftyJson 解析 json 响应。以下是我的代码和回复