2011-02-18 27 views
25

đâu JSON_CATEGORY_DATA_URL_STRING là URL feed của tôi, mà trả về tốt như:Chuyển đổi thức ăn JSON để NSDictionary

[ 
    { 
     "group":"For Sale", 
     "code":"SSSS" 
    }, 
    { 
     "group":"For Sale", 
     "category":"Wanted", 
     "code":"SWNT" 
    } 
] 

tôi dường như không thể có được một đẹp NSDictionary (hoặc NSArray) ra khỏi đoạn mã sau:

+ (NSDictionary *)downloadJSON 
{ 

NSDictionary *json_string; 
NSString *dataURL = [NSString stringWithFormat:@"%@", JSON_CATEGORY_DATA_URL_STRING]; 
NSLog(@"%@",dataURL); 
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:dataURL]];  
NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil]; 

json_string = [[[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding]autorelease]; 
NSDictionary *json_dict = (NSDictionary *)json_string; 
NSLog(@"json_dict\n%@",json_dict); 
    NSLog(@"json_string\n%@",json_string); 

return json_string; 
} 

Tôi đã đọc nhiều bài viết về điều này, nhưng tôi không nhận được.

+0

CHỈNH SỬA: đang sử dụng SBJSON – linkingarts

+0

Cũng FWIW, JSONValue chỉ trả về giá trị rỗng? – linkingarts

+2

Vâng ... hóa ra đó là một nguồn cấp dữ liệu không tốt. Mã ban đầu là tốt (ngay cả trước khi viết lại 6 lần và đăng ở đây). – linkingarts

Trả lời

8

Bạn không thể chỉ tạo chuỗi làm từ điển và mong đợi nó phân tích cú pháp JSON. Bạn phải sử dụng thư viện phân tích cú pháp JSON để lấy chuỗi đó và chuyển đổi nó thành từ điển.

+2

Để biết danh sách các thư viện JSON cho Objective-C, hãy xem http://cocoaobjects.com/?s=json –

1

Bạn cần sử dụng trình phân tích cú pháp JSON. đây là mã đã chỉnh sửa

+ (NSDictionary *)downloadJSON 
{ 

NSDictionary *json_string; 
NSString *dataURL = [NSString stringWithFormat:@"%@", JSON_CATEGORY_DATA_URL_STRING]; 
NSLog(@"%@",dataURL); 
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:dataURL]];  
NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil]; 

json_string = [[[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding]autorelease]; 
//JSONValue is a function that will return the appropriate object like dictionary or array depending on your json string. 
NSDictionary *json_dict = [json_string JSONValue]; 
NSLog(@"json_dict\n%@",json_dict); 
    NSLog(@"json_string\n%@",json_string); 

return json_dict; 
} 

đây phải là mã để lấy từ điển NSD. nhưng bạn json chuỗi là một mảng để thay vì sử dụng.

+ (NSArray *)downloadJSON 
{ 

NSDictionary *json_string; 
NSString *dataURL = [NSString stringWithFormat:@"%@", JSON_CATEGORY_DATA_URL_STRING]; 
NSLog(@"%@",dataURL); 
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:dataURL]];  
NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil]; 

json_string = [[[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding]autorelease]; 
NSArray *json_dict = [json_string JSONValue]; 
NSLog(@"json_dict\n%@",json_dict); 
    NSLog(@"json_string\n%@",json_string); 

return json_dict; 
} 

Chỉnh sửa: bạn cần sử dụng JSON.framework để gọi phương thức JSONValue.
cũng cần phải trả lại json_dict thay vì json_string làm json_stringNSString loại và không NSDictionary hoặc NSArray.
và không tự động sửa nó, vì đó là biến lớp học của bạn

+0

ngay cả khi NSArray tôi vẫn nhận được json_dict null. Ngoài ra, cảnh báo "NSArray (hoặc NSDict) có thể không phản hồi JSONValue" – linkingarts

+0

bạn đã nhập 'trình phân tích cú pháp JSON' vào tệp tiêu đề của mình hay chưa. – Robin

+0

yes: #import "JSON.h" – linkingarts

96

Với IOS5 bạn có thể sử dụng NSJSONSerialization để tuần tự hóa JSON.

NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error]; 

Hy vọng điều này sẽ giúp bạn.

+2

NSJSONWritingPrettyPrinted là một tùy chọn viết để sử dụng trong writeJSONObject :, nếu bạn sử dụng nó trong ngữ cảnh này, bạn sẽ nhận được hiệu quả của NSJSONReadingMutableContainers áp dụng cho việc đọc. – Nick

+0

Tôi đã sử dụng cùng một 'NSData * jsonData = [NSJSONSerialization dataWithJSONObject: tùy chọn tham số: NSJSONWritingPrettyPrinted error: & writeError]; // NSString * strJsonRequest = [[NSString alloc] initWithData: mã hóa jsonData: NSUTF8StringEncoding]; NSDictionary * dicJsonRequest = [NSJSONSerialization JSONObjectWithData: jsonData tùy chọn: kNilOptions lỗi: & convertError]; ' Nó chuyển đổi chuỗi thành công nhưng cho dicationary nó không được chuyển đổi sang định dạng json – Heena

+0

Lỗi cũng là null.what là sai với dòng này.Tôi có bản sao dán mã của bạn – Heena

2

Tôi đã tạo một lớp giúp nhiệm vụ này dễ dàng hơn. Nó sử dụng NSJSONSerialization của iOS 5. Sao chép nó từ github here.

0

tạo phương pháp để tìm nạp dữ liệu.Chọn url của bạn trong urlwithstring.

-(void)fetchjsondata 
{ 
    NSString *login= [[NSString stringWithFormat:@"your url string"]stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; 

    NSLog(@"----%@", login); 
    NSURL *url = [NSURL URLWithString:[login stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]; 
    //-- Get request and response though URL 
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc]initWithURL:url]; 


    [NSURLConnection sendAsynchronousRequest:request 
             queue:[NSOperationQueue mainQueue] 
          completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) { 
           dispatch_async(dispatch_get_main_queue(), ^{ 
            if (data) { 
             dic_property= [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil]; 
             NSLog(@"%@", dic_property); 
             NSLog(@"counts=%d",[[dic_property objectForKey:@"Data"]count]); 



            } 
            else { 
             NSLog(@"network error, %@", [error localizedFailureReason]); 
            } 
           }); 

          }]; 

} 

gọi fetchjsonmethod ở bất kỳ đâu.

[NSThread detachNewThreadSelector: @selector (fetchdata) toTarget: self withObject: nil];

Các vấn đề liên quan