Objective C 从 URL 读取 JSON 到 NSDictionary [英] Objective C read JSON from URL into NSDictionary

查看:37
本文介绍了Objective C 从 URL 读取 JSON 到 NSDictionary的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我正在制作一个获取用户当前位置的应用程序,然后将纬度和经度坐标发送到此 URL 以查看附近有哪些所需的商店.我能够做我刚才提到的所有事情,但我不确定如何阅读网页内容的内容并使用它来形成表格视图/按最短距离排列等.我做了一些研究并发现这是JSON,并设法使用 NSJSONSerialization 将 URL 中的内容解析为 NSDictionary.我不确定的是如何读取包含 JSON 语法的 NSDictionary 的内容.我需要诸如姓名"、距离"、格式化地址"之类的键,并按距离"升序排列在 UITableView 中的数据.

So I am making an application that gets the users current location, then sends the Latitude and Longitude coordinates to this URL to see which desired stores are nearby. I am able to do everything I just mentioned, but am not sure how to read the content of the content of the webpage and use it to form a table view/ arrange it by shortest distance etc. I did some research and figured out this is JSON, and managed to parse the content from the URL into a NSDictionary with NSJSONSerialization. What I am not sure about is how to read the content of the NSDictionary containing the JSON syntax. I need keys like 'name', 'distance', 'formatted address', and to arrange my data in a UITableView by sorted 'distance' in ascending order.

这是我从 URL 获取的 JSON 脚本的屏幕截图:

Here is a screenshot of the JSON script i GET from the URL:

推荐答案

这是访问不同场所的 NSArray 的方法:

This is how you can access an NSArray of the different venues:

  NSArray* locationsArray = jsonDictionary[@"response"][@"venues"];

从那里您可以访问所有位置数据.我将使用 CLLocation 属性为这些位置创建一个新的模型类来存储经度和纬度以及距离属性.遍历数组并实例化模型,同时计算与设备当前位置的距离:

From there you have access to all the location data. I would create a new model class for these locations with a CLLocation property to store the longitude and latitude as well as a distance property. Iterate through the array and instantiate the models while also calculating the distance from the device's current location:

NSMutableArray *locationObjectsArray;
for (NSDictionary *locationDict in locationsArray)
{
    Location *newLocation = [Location alloc] initWith...];
    newLocation.distance = [newLocation.coordinate distanceFromLocation:deviceLocation];
    [locationObjectsArray addObject:newLocation];
}

NSArray * results = [sortedLocations sortedArrayUsingDescriptors:@[[[NSSortDescriptor alloc] initWithKey:@"distance"
                                                                              ascending:YES]]];

这应该会为您提供按距离设备的距离排序的位置数组,您现在可以将其显示在表格中.

This should give you an array of locations sorted by distance from the device which you can now display in a table.

这篇关于Objective C 从 URL 读取 JSON 到 NSDictionary的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆