我有一个 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/