Ios 从NSMutableArray解析Objective C JSON

Ios 从NSMutableArray解析Objective C JSON,ios,objective-c,json,Ios,Objective C,Json,我有一个类似下面的JSON(从URL获取)—— 下面的代码是从URL获取JSON并将其存储在NSMutableArray中。在将它们存储到数组中之前,它工作正常,但我对JSON格式有点困惑,不知道如何通过键获得结果 __block NSMutableArray *jsonArray = nil; [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES]; NSString *urlString = [NS

我有一个类似下面的JSON(从URL获取)——

下面的代码是从URL获取JSON并将其存储在NSMutableArray中。在将它们存储到数组中之前,它工作正常,但我对JSON格式有点困惑,不知道如何通过键获得结果

__block NSMutableArray *jsonArray = nil;
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];
NSString *urlString = [NSString stringWithFormat:@"http://xxxxxxx/api.php?action=getAllJournal"];
NSURLRequest * request = [NSURLRequest requestWithURL:[NSURL URLWithString:urlString]];
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * response, NSData * data, NSError * connectionError)
 {
     if (data)
     {
         id myJSON;
         @try {
             myJSON = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
         }
         @catch (NSException *exception) {
         }
         @finally {
         }
         jsonArray = (NSMutableArray *)myJSON;

         NSString *nsstring = [jsonArray description];
         NSLog(@"IN STRING -> %@",nsstring);

         NSData *data = [nsstring dataUsingEncoding:NSUTF8StringEncoding];
         NSError *jsonError;
         NSDictionary *jsonObject = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&jsonError];
         if(jsonObject !=nil){

             if(![[jsonObject objectForKey:@"journalList"] isEqual:@""]){

                 NSMutableArray *array=[jsonObject objectForKey:@"journalList"];

                 NSLog(@"array: %lu",(unsigned long)array.count);

                 int k = 0;
                 for(int z = 0; z<array.count;z++){

                     NSString *strfd = [NSString stringWithFormat:@"%d",k];
                     NSDictionary *dicr = jsonObject[@"journalList"][strfd];
                     k=k+1;
                     // NSLog(@"dicr: %@",dicr);
                     NSLog(@"cust_code - journal_amount   : %@ - %@",
                           [NSMutableString stringWithFormat:@"%@",[dicr objectForKey:@"cust_code"]],
                           [NSMutableString stringWithFormat:@"%@",[dicr objectForKey:@"journal_amount"]]);
                 }

             }

         }else{
             NSLog(@"Error - %@",jsonError);
         }

     }
 }];
\u块NSMUTABLEARRY*jsonArray=nil;
[[UIApplication sharedApplication]设置网络活动指示器可见:是];
NSString*urlString=[NSString stringWithFormat:@]http://xxxxxxx/api.php?action=getAllJournal"];
NSURLRequest*request=[NSURLRequest requestWithURL:[NSURL URLWithString:urlString]];
[NSURLConnection sendAsynchronousRequest:请求队列:[NSOperationQueue mainQueue]完成处理程序:^(NSURResponse*response,NSData*data,NSError*connectionError)
{
如果(数据)
{
id myJSON;
@试一试{
myJSON=[NSJSONSerialization JSONObjectWithData:数据选项:NSJSONReadingMutableContainers错误:nil];
}
@捕获(NSException*异常){
}
@最后{
}
jsonArray=(NSMutableArray*)myJSON;
NSString*NSString=[jsonArray description];
NSLog(@“在字符串中->%@”,nsstring);
NSData*data=[nsstring DATAUSINGENCODE:NSUTF8StringEncoding];
n错误*jsonError;
NSDictionary*jsonObject=[NSJSONSerialization jsonObject WithData:数据选项:针织错误:&jsonError];
if(jsonObject!=nil){
如果(![[jsonObject objectForKey:@“journalList”]isEqual:@“”){
NSMutableArray*数组=[jsonObject objectForKey:@“JournallList”];
NSLog(@“数组:%lu”,(无符号长)array.count);
int k=0;

对于(intz=0;z您需要从
数据中获取
日志列表

请尝试以下代码:

这是创建类似您的阵列的演示代码:

NSMutableDictionary *jsonObject = [NSMutableDictionary new];
jsonObject[@"action"]= @"";
jsonObject[@"message"]= @"";
jsonObject[@"message_code"]= @"";
jsonObject[@"result"]= @"1";
NSMutableArray *ary1 = [NSMutableArray new];
for(int i=0;i<5;i++)
{
    NSMutableDictionary *dd = [NSMutableDictionary new];
    dd[@"cancelled"]= @"F";
    dd[@"cust_code"]= @"F";
    [ary1 addObject:dd];
}


NSMutableDictionary *dicjournal = [NSMutableDictionary new];
[dicjournal setObject:ary1 forKey:@"journalList"];
[jsonObject setObject:dicjournal forKey:@"data"];

您需要从
数据
中获取
日志列表

请尝试以下代码:

这是创建类似您的阵列的演示代码:

NSMutableDictionary *jsonObject = [NSMutableDictionary new];
jsonObject[@"action"]= @"";
jsonObject[@"message"]= @"";
jsonObject[@"message_code"]= @"";
jsonObject[@"result"]= @"1";
NSMutableArray *ary1 = [NSMutableArray new];
for(int i=0;i<5;i++)
{
    NSMutableDictionary *dd = [NSMutableDictionary new];
    dd[@"cancelled"]= @"F";
    dd[@"cust_code"]= @"F";
    [ary1 addObject:dd];
}


NSMutableDictionary *dicjournal = [NSMutableDictionary new];
[dicjournal setObject:ary1 forKey:@"journalList"];
[jsonObject setObject:dicjournal forKey:@"data"];

这不是有效的JSON。条目应该用逗号分隔,
,而不是分号;

这不是有效的JSON。条目应该用逗号分隔,
,,而不是分号;

看起来您的JSON是无效的。您可以查看您的JSON是否正确使用,并对其进行格式化。意思是ile您的代码没有使用“数据”键获取“日志列表”数组

代码:-

NSDictionary *dic = [jsonObject valueForKey:@"data"];

NSMutableArray *arr = [dic objectForKey:@"journalList"];

for (int index=0 ; index < arr.count ; index++){

NSDictionary *obj = [arr objectAtIndex:index];

// Now use object for key from this obj to get particular key 

}
NSDictionary*dic=[jsonObject valueForKey:@“data”];
NSMUTABLEARRY*arr=[dic objectForKey:@“日志列表”];
for(int index=0;index
看起来您的JSON无效。您可以查看您的JSON是否正确并使用它进行格式化。同时,您的代码没有使用“数据”键获取“日志列表”数组

代码:-

NSDictionary *dic = [jsonObject valueForKey:@"data"];

NSMutableArray *arr = [dic objectForKey:@"journalList"];

for (int index=0 ; index < arr.count ; index++){

NSDictionary *obj = [arr objectAtIndex:index];

// Now use object for key from this obj to get particular key 

}
NSDictionary*dic=[jsonObject valueForKey:@“data”];
NSMUTABLEARRY*arr=[dic objectForKey:@“日志列表”];
for(int index=0;index
有一个名为“data”的字典,您无法获取,它由{}表示

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

if (!jsonError) {

    // Fetch the journalList
    NSArray *journalList = json[@"data"][@"journalList"];

    // iterate over every entry and output the wanted values
    for (NSDictionary *journal in journalList) {
        NSLog(@"%@ %@", journal[@"cust_code"], journal[@"journal_amount"]);
    }
}

json[@“key”]是[json objectForKey:@“key”]的一种简短形式,我发现它更容易阅读。

有一个名为“data”的字典,您无法获取,它由{}表示

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

if (!jsonError) {

    // Fetch the journalList
    NSArray *journalList = json[@"data"][@"journalList"];

    // iterate over every entry and output the wanted values
    for (NSDictionary *journal in journalList) {
        NSLog(@"%@ %@", journal[@"cust_code"], journal[@"journal_amount"]);
    }
}

json[@“key”]是[json objectForKey:@“key”]的缩写形式,我发现它更容易阅读。

谢谢@Larme和@Amset的帮助。我在
NSMutableArray
部分做了错误的操作。下面是此代码的正确版本:

[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];
NSString *urlString = [NSString stringWithFormat:@"http://xxxxxxx/api.php?action=getAllJournal"];
NSURLRequest * request = [NSURLRequest requestWithURL:[NSURL URLWithString:urlString]];
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * response, NSData * data, NSError * connectionError)
 {
     if (data)
     {
         id myJSON;
         @try {
             myJSON = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
         }
         @catch (NSException *exception) {
         }
         @finally {
         }

         NSArray *journalList = myJSON[@"data"][@"journalList"];
         for (NSDictionary *journal in journalList) {
             NSLog(@"%@ %@", journal[@"journal_date"], journal[@"journal_amount"]);
         }
     }
 }];

感谢@Larme和@Amset的帮助。我在
NSMutableArray
部分中做错了。下面是此代码的正确版本:

[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];
NSString *urlString = [NSString stringWithFormat:@"http://xxxxxxx/api.php?action=getAllJournal"];
NSURLRequest * request = [NSURLRequest requestWithURL:[NSURL URLWithString:urlString]];
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * response, NSData * data, NSError * connectionError)
 {
     if (data)
     {
         id myJSON;
         @try {
             myJSON = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
         }
         @catch (NSException *exception) {
         }
         @finally {
         }

         NSArray *journalList = myJSON[@"data"][@"journalList"];
         for (NSDictionary *journal in journalList) {
             NSLog(@"%@ %@", journal[@"journal_date"], journal[@"journal_amount"]);
         }
     }
 }];
我会说:

我不会对
NSJSONSerialization
进行@try/@catch,因为真正的问题在于
错误
参数(在大多数情况下,它们不会抛出
NSException
),只需检查
是否(数据)
相当有效

然后,假设它成功了,您有了
myJSON
。 事实上,
myJSON
是一个
NSDictionary
,而不是一个
NSArray
,因此强制转换是无用的,没有意义

下一期: 您正在使用
-description
(好的,如果您想调试的话),但是您不能使用它来重新构建JSON。它不是有效的JSON,这是编译器“打印”对象、添加“;”等的方式。 如果打印
[nsstring dataUsingEncoding:NSUTF8StringEncoding]
数据
,您会发现它们不一样。 欲了解更具可读性的信息:
NSString*dataJSONStr=[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
,它的结构显然不同于您的
NSString

那么,您是在重做JSON序列化吗?为什么

因此:

我会说:

我不会对
NSJSONSerialization
进行@try/@catch,因为真正的问题在于
错误
参数(在大多数情况下,它们不会抛出
NSException
),只需检查
是否(数据)
相当有效

然后,假设它成功了,您有了
myJSON
。 事实上,
myJSON
是一个
NSDictionary
,而不是一个
NSArray
,因此强制转换是无用的,没有意义

下一期: 您正在使用
-description
(好的,如果您想调试的话),但是您不能使用它来重新构建JSON。它不是有效的JSON,这是编译器“打印”对象、添加“;”等的方式。 如果打印
[nsstring dataUsingEncoding:NSUTF8StringEncoding]
数据
,您会发现它们不一样。 更多阅读