将NSData转换为NSDictionary

时间:2011-08-18 14:58:23

标签: ios xml nsdictionary nsdata

我从XML文件中获取数据,并将其存储在NSData对象中。我想将NSData转换为NSDictionary并将该数据存储在plist中。

我的代码如下:

NSURL *url = [NSURL URLWithString:@"http://www.fubar.com/sample.xml"];
    NSData *data = [NSData dataWithContentsOfURL:url]; 
    NSLog(@"%@", data);

要转换数据,我正在使用:

- (NSDictionary *)downloadPlist:(NSString *)url {
    NSMutableURLRequest *request  = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url] cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:10]; 
    NSURLResponse *resp = nil;
    NSError *err = nil;
    NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&resp error:&err];

    if (!err) {
        NSString *errorDescription = nil;
        NSPropertyListFormat format;
        NSDictionary *samplePlist = [NSPropertyListSerialization propertyListFromData:responseData mutabilityOption:NSPropertyListImmutable format:&format errorDescription:&errorDescription];

        if (!errorDescription)
            return samplePlist;

        [errorDescription release];              
    }

    return nil;
}

有人可以告诉我该怎么做吗?

2 个答案:

答案 0 :(得分:5)

或者这个:

NSString* dataStr  = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];   
SBJSON *jsonParser = [SBJSON new];
NSDictionary* result = (NSDictionary*)[jsonParser objectWithString:dataStr error:nil];
[jsonParser release];
[dataStr release];

答案 1 :(得分:2)

试试这段代码:

NSString *newStr1 = [[NSString alloc] initWithData:theData1 encoding:NSUTF8StringEncoding];
NSString *newStr2 = [[NSString alloc] initWithData:theData2 encoding:NSUTF8StringEncoding];
NSString *newStr3 = [[NSString alloc] initWithData:theData3 encoding:NSUTF8StringEncoding];

NSArray *keys = [NSArray arrayWithObjects:@"key1", @"key2", @"key3", nil];
NSArray *objects = [NSArray arrayWithObjects:newStr1 , newStr2 , newStr3 , nil];
NSDictionary *dictionary = [NSDictionary dictionaryWithObjects:objects forKeys:keys];

for (id key in dictionary) {
    NSLog(@"key: %@, value: %@", key, [dictionary objectForKey:key]);
}

NSString *path = [[NSBundle mainBundle] pathForResource:@"Login" ofType:@"plist"]; 
[dictionary writeToFile:path  atomically:YES];
//here Login is the plist name.

快乐编码