从json输出为类实例分配值

时间:2016-10-24 05:07:56

标签: ios objective-c json

我正在编写一个代码来创建一个应用程序,其中一组问题及其选项和答案正由json解析获取。我在viewDidLoad方法中做了这一切。

这是到目前为止的代码。解析代码工作正常。

- (void)viewDidLoad {
[super viewDidLoad];
question *quest = [[question alloc] init];
//Parsing code

NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:@"http://***/****/fetch.php"]];
[request setHTTPMethod:@"POST"];
NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
[[session dataTaskWithRequest:request completionHandler:^(NSData *data , NSURLResponse *response , NSError *error){
    NSError *err = nil;
    id jsonData = [NSJSONSerialization JSONObjectWithData:data options:0 error:&err];
    if (err) {
        [self alertMessage:(@"%@", err)];
    }
    else {

//Unclear from here   


        NSLog(@"%@", jsonData[@"data"]);
        allData = jsonData[@"data"];
        NSLog(@"%lu",(unsigned long)allData.count);
        int count = allData.count;
        int i = 0;
        while (i < count){
            question *que;
            NSString *q,*a,*o1,*o2,*o3,*o4;
            a = [allData valueForKey:@"answer"];
            q = [allData valueForKey:@"question"];
            o1 = [allData valueForKey:@"option1"];
            o2 = [allData valueForKey:@"option2"];
            o3 = [allData valueForKey:@"option3"];
            o4 = [allData valueForKey:@"option4"];

            //NSLog(@"%@", [allData valueForKey:@"question"]);
            [que setValue:q forKey:@"question"];
            [que setValue:a forKey:@"answer"];
            [que setValue:o1 forKey:@"option1"];
            [que setValue:o2 forKey:@"option2"];
            [que setValue:o3 forKey:@"option3"];
            [que setValue:o4 forKey:@"option4"];
            i++;

            NSLog(@"%@",[que valueForKey:@"question"]);
        }

    }
}] resume];

}

以下是NSLog(@"%@", jsonData[@"data"]);代码在控制台中的输出结果。

{
        answer = sometext;
        id = 7;
        option1 = sometext;
        option2 = sometext;
        option3 = sometext;
        option4 = sometext;
        question = "sometext";
    },           
        {
        answer = sometext;
        id = 9;
        option1 = sometext;
        option2 = sometext;
        option3 = sometext;
        option4 = sometext;
        question = "sometext";
    }
)

据我所知,这个json数据是一个字典数组(?)

我要做的下一步是创建了一个&#34;问题&#34;类。我不确定我是否做得对,但这里是代码:

#import "question.h"
@implementation question {    
NSString *q;
NSString *a;
NSString *o1;
NSString *o2;
NSString *o3;
NSString *o4;       
}
@end

viewDidLoad方法的while循环中,我尝试创建名为question的{​​{1}}类的实例,我试图填充该类,如图所示代码。 但是行que在控制台中提供了NSLog(@"%@",[que valueForKey:@"question"]);

我确定我使用的方法有问题。

第二个问题是,我正在创建一个名为null的{​​{1}}数组,我在question之后立即声明。但是,我无法在任何其他代码块中使用它,例如按钮的单击事件。如果我尝试使用quest上方的viewDidLoad行,则会出错:

question *quest = [[question alloc] init];

我知道这不是理想的编码方式,但我仍然是这里的初学者,我只是对所有这些新概念感到困惑。我在Swift中开发了相同的应用程序,但Objective C感觉太难了。 任何帮助将不胜感激。

2 个答案:

答案 0 :(得分:1)

任务未声明为数组。在类定义中声明数组(在.h文件中)。例如 -

  NSMutableArray *questionsArray;

确保在开始尝试在数据解析中添加数据之前对其进行初始化(您应该将解析移动到自己的方法中,而不是在viewDidLoad方法中);

 questionsArray = [[NSMutableArray alloc] initWithCapacity:20];

您可以使用键/值属性,但类似于

  que.answer = [allData valueForKey:@"question"];

更干净(imo)。解析完问题后,您可以像这样将它添加到数组中;

  [questionsArray addObject:que];

答案 1 :(得分:1)

首先要获得你想要的东西,你必须创建一个NSMutableArray,它将存储Question Class的实例,你必须将它声明为像这样的全局数组

<html>
<body>

<p id="demo"></p>

<script>
var firstdate = '2012-11-21';
var seconddate = '2012-11-21';
if( (new Date(firstdate).getTime() > new Date(seconddate).getTime()))
{
 document.getElementById("demo").innerHTML = "firstdate is greater";
}
else if( (new Date(firstdate).getTime() < new Date(seconddate).getTime()))
{
 document.getElementById("demo").innerHTML = "first date is not greater";
}
else if( (new Date(firstdate).getTime() == new Date(seconddate).getTime()))
{
 document.getElementById("demo").innerHTML = "first date is equal";
}
else
{
 document.getElementById("demo").innerHTML = "date format is not correct";
}
</script>

</body>
</html>

现在,在question.h中,你必须为这样的所有变量声明@interface MyClass () { NSMutableArray * arrQuestion; } ,同样问题类将从NSObject派生,因为你将它创建为@property类< / p>

Model

现在在while循环中你必须创建Question类的新实例,并且必须像这样分配值

@interface question : NSObject
@property (nonatomic, strong) NSString *strQuestion;
@property (nonatomic, strong) NSString * strAnswer;
@property (nonatomic, strong) NSString * strOptionA;
@property (nonatomic, strong) NSString * strOptionB;
@property (nonatomic, strong) NSString * strOptionC;
@property (nonatomic, strong) NSString * strOptionD;  
@end

现在从arrQuestion = [NSMutableArray new]; while (i < count){ question *quest = [[question alloc] init]; quest.strQuestion = [[[jsonData objectForKey:@"data"]objectAtIndex:i] objectForKey:@"question"]; quest.strAnswer = [[[jsonData objectForKey:@"data"]objectAtIndex:i] objectForKey:@"answer"]; quest.strOptionA = [[[jsonData objectForKey:@"data"]objectAtIndex:i] objectForKey:@"option1"]; quest.strOptionB = [[[jsonData objectForKey:@"data"]objectAtIndex:i] objectForKey:@"option2"]; quest.strOptionC = [[[jsonData objectForKey:@"data"]objectAtIndex:i] objectForKey:@"option3"]; quest.strOptionD = [[[jsonData objectForKey:@"data"]objectAtIndex:i] objectForKey:@"option4"]; i++; [arrQuestion addObject:quest]; } 您可以访问像这样的值

arrQuestion