2012-07-04 153 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文章有一個非常簡單的方法。我建議閱讀。