2012-07-04 154 views
0

我有一个PHP web服务,返回一个JSON字符串格式:如何从JSON NSDictionary中创建对象

[{"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 

然后,使用其他类的主要应用I'm:

#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对象的数组。

任何人都可以帮助我吗?

感谢提前:)

+0

[iOS中的原生JSON支持?]的可能的重复(http://stackoverflow.com/questions/3562478/native-json-support-in-ios) – Monolo

回答

4

这样做:

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"]]; 
+0

不错!这解决了我的问题,没有更多的麻烦。谢谢!! – miguelmsa1

1

这也是阅读JSON获得更好的性能,当使用多线程一个很好的做法。 This文章有一个非常简单的方法。我建议阅读。