从json数据获取特定索引这样的学生姓名

问题描述 投票:0回答:1

我在iOS中开发简单的应用程序,获取数据web api我的代码正确地返回了json数据但是当我想要特定的例如来自json的学生名称返回null。这是我的数据:

{
Sudent( 
{
    {"id":"20",
    "name":"Alan",
    "email":"[email protected]",
    "phone":"1234567890",
    "location":"London"},
 {  
"id":"40",
    "name":"John",
    "email":"[email protected]",
    "phone":"1234567890",
    "location":"usa"},
"id":"50",
    "name":"Nora",
    "email":"[email protected]",
    "phone":"1234567890",
    "location":"kenya"}, 

})}

这里我的代码将数据作为json获取并存储名为Student的NSMutableArray:

-(void)proxydidFinishLoadingData:(id)data InMethod:(NSString*)method
{
    if ([method isEqualToString:@"getstudentdata"]){

       defaultDict = [[NSMutableDictionary alloc]init];
         [defaultDict addEntriesFromDictionary:[NSJSONSerialization JSONObjectWithData:[data dataUsingEncoding:NSUTF8StringEncoding] options:0 error:nil]];
         Student = [defaultDict objectForKey:@"data"];

    }
}

这个代码它工作正常并且正确并返回了json数据,但问题是当我想得到特定的索引,例如学生的名字时,它不起作用,它返回null值。执行此工作的代码在这里:

NSMutableDictionary *response = [[defaultDict valueForKey:@"data"] mutableCopy];
    NSString *name = [[response valueForKey:@"name"]];
   ];

      NSLog(@"%@" ,name);

请帮助我获取学生姓名

ios objective-c json
1个回答
0
投票

您正在“数据”键中检查“名称”键,但实际上它存在于“学生”键中。

Parse to Student对象并使用for循环逐个获取“name”键值。

使用此网站http://www.json4swift.com/创建模型。(只需要在此处输入JSON响应)。

Var dataModelArray = [Your_Model_Type]()
if let data = data[“student”] as? [String: AnyObject]  {
  dataModelArray = Your_Model_type.modelsFromDictionaryArray(array: data)
}

//你的dataModelArray中有数据数组//你可以像这样访问

dataModelArray[0].name
© www.soinside.com 2019 - 2024. All rights reserved.