首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何将json字符串解析为nsdictionary?

如何将json字符串解析为nsdictionary?
EN

Stack Overflow用户
提问于 2012-04-06 17:37:46
回答 4查看 23.6K关注 0票数 19

我正在为登录应用程序编写代码。有人能帮我解析一个json字符串吗?我的代码是

代码语言:javascript
复制
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{

    NSString *loginStatus = [[NSString alloc] initWithBytes: [webData mutableBytes] length:[webData length] encoding:NSUTF8StringEncoding];

    SBJsonParser *parser = [[SBJsonParser alloc] init];

    NSArray *loginDict = [parser objectWithString:loginDict error:nil];

    [loginStatus release];

    [connection release];
EN

回答 4

Stack Overflow用户

回答已采纳

发布于 2012-04-06 19:36:54

示例数据:

代码语言:javascript
复制
NSString *strData = @"{\"1\": {\"name\": \"Jerry\",\"age\": \"12\"}, \"2\": {\"name\": \"Bob\",\"age\": \"16\"}}";
NSData *webData = [strData dataUsingEncoding:NSUTF8StringEncoding];

NSError *error;
NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:webData options:0 error:&error];
NSLog(@"JSON DIct: %@", jsonDict);

NSLog输出:

代码语言:javascript
复制
JSON DIct: {
     1 =     {
         age = 12;
         name = Jerry;
     };
     2 =     {
         age = 16;
         name = Bob;
     };
}
票数 50
EN

Stack Overflow用户

发布于 2012-11-21 16:57:36

代码语言:javascript
复制
//*************Static Resopnse
NSString *filePath = [[NSBundle mainBundle] pathForResource:@"demo" ofType:@"text"];
NSLog (@"Content: %@", filePath);
NSString *content = [[[NSString alloc] initWithContentsOfFile:filePath
                                                 usedEncoding:nil
                                                        error:nil] autorelease];

SBJSON *json = [[SBJSON new] autorelease];
NSString *str=[[NSString alloc]initWithString:content];
dictTemp = [json objectWithString:str error:nil];
NSLog(@"Actions is: %@",dictTemp);
NSArray *arr=[[dictTemp valueForKey:@"Data"] mutableCopy];
arrX=[[NSMutableArray alloc] init];
arrY=[[NSMutableArray alloc] init];

for(NSDictionary *dict in arr)
{
    [arrX addObject:[dict valueForKey:@"Milestone"]];
    [arrY addObject:[dict valueForKey:@"Sites"]];
}   
NSLog(@"X is: %@",[arrX description]);
NSLog(@"Y is: %@",[arrY description]);
票数 0
EN

Stack Overflow用户

发布于 2012-04-06 17:44:56

代码语言:javascript
复制
NSString *loginStatus = [[NSString alloc] initWithBytes: [webData mutableBytes] length:[webData length] encoding:NSUTF8StringEncoding]
NSLog([[loginStatus JSONValue] description],nil);

//This will give you parsed output.
票数 -1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/10041689

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档