ios - 如何从 JSON NSDictionary 创建对象

标签 ios json cocoa object nsdictionary

我有一个 PHP Web 服务,它返回一个 JSON 字符串,格式如下:

[{"latitud":"37.995914","longitud":"-1.139705","nombre":"Miguel de 
Unamuno"},{"latitud":"37.995433","longitud":"-1.140143","nombre":"Calle
 Pina"},{"latitud":"37.99499","longitud":"-1.140361","nombre":"Calle 
Moncayo"},{"latitud":"37.993918","longitud":"-1.139392","nombre":"Calle 
Moncayo2"},{"latitud":"37.994588","longitud":"-1.138543","nombre":"Calle 
Salvador de Madriaga"}]

在我的项目中,我有一个具有下一个结构的自定义类:

#import <Foundation/Foundation.h>
#import <MapKit/MapKit.h>

@interface PCoordenada : NSObject

@property (nonatomic) CLLocationCoordinate2D *punto;
@property (nonatomic,strong) NSString *nombre;
@end

然后,我为主应用程序使用其他类:

#import <UIKit/UIKit.h>
#import "PCoordenada.h"

@interface TestViewController : UIViewController

@property (nonatomic,strong) NSData * HTTPResponse;
@property (nonatomic,strong) NSDictionary * dic;
@property (nonatomic,strong) NSMutableArray *arrayCoord;
@property (nonatomic,strong) PCoordenada *coor;

-(IBAction)GetDataFrom:(id)sender;

@end

我想知道如何制作包含 JSON 字符串信息的 PCoordenada 对象数组。

谁能帮帮我?

提前致谢:)

最佳答案

这样做:

NSData *theData = [NSData dataWithContentsOfURL:[NSURL URLWithString:YOUR_URL]];
NSArray *arrRequests = [NSJSONSerialization JSONObjectWithData:theData options:NSJSONReadingMutableContainers error:nil];

这会将 JSON 放入对象的 NSArray 中。这些对象中的每一个都是一个 NSDictionary。因此,您只需要遍历 NSArray 以获取每个 NSDictionary。

//now let's loop through the array and generate the necessary annotation views
for (int i = 0; i<= arrRequests.count - 1; i++) {
    //now let's dig out each and every json object
    NSDictionary *dict = [arrRequests objectAtIndex:i];}

您从循环中获得的每个 NSDictionary 都将 JSON 属性作为 NSDictionary 中的键:

 NSString *address = [NSString stringWithString:[dict objectForKey:@"Address"]];

关于ios - 如何从 JSON NSDictionary 创建对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11332509/

相关文章:

python - 在 python 中使用 pandas 从嵌套结构中构建数据框

javascript - 这是无效的 JSON 吗?

objective-c - NSDate 和第二天

objective-c - 等效键删除在 cocoa 应用程序中不起作用

objective-c - 更改 -observeValueForKeyPath :ofObject:change:context: 中的属性时,Cocoa 绑定(bind)不起作用

ios - 具有动态按钮列表的操作表类型的 UIAlertViewController

android - 对于 DOM 解析器来说,多大的 xml 文件应该被认为太大?

ios - 应用卡在 dispatch_async 中

ios - 对 MS Graph API 的请求给了我 "Authorization Request Denied - Insufficient privileges to complete the operation"

javascript - Angular 翻译多个 json 文件