JSON解析器不起作用

时间:2014-07-28 08:55:32

标签: ios objective-c json

前几天我尝试从服务器读取和解析数据。但今天它不起作用。有什么不对? 在这里,我出了我的方法:

 -(void) getDataFromServer
 {
     act = @"linkinginit";
     deviceid = @"1xyhgjs";
     fullRequest = [NSString stringWithFormat:@"http://app.ivson.by/?act=%@&deviceid=%@",    act, deviceid];
    NSLog(@"%@", fullRequest);
    NSURL *url = [NSURL URLWithString:fullRequest];
    NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:url];

    NSData *returnData = [NSURLConnection sendSynchronousRequest: theRequest returningResponse: nil error: nil];


  NSString *strData = [[NSString alloc]initWithData:returnData encoding:NSUTF8StringEncoding];
  NSRange   searchedRange = NSMakeRange(0, [strData length]);
  NSLog(@"Data from server = %@", strData);
  NSString *json = strData;
    //   NSString *json = @"{\"code\":200,\"serviceID\":\"53d22b10e46a5\",\"sender\":1,\"hasPair\":0}";
   NSData *jsonData = [json dataUsingEncoding:NSUTF8StringEncoding];
   NSError *error = nil;
   id obj = [NSJSONSerialization JSONObjectWithData:jsonData
                                         options:0
                                           error:&error];
if (obj) {
    NSAssert([obj isKindOfClass:[NSDictionary class]], @"Expected a dictionary");
    NSDictionary *dictObj = (NSDictionary *)obj;
    NSNumber *code = dictObj[@"code"];
    NSLog(@"code:", code);
    NSString *serviceId = dictObj[@"serviceID"];
    NSLog(@"serviceId:", serviceId);
    NSNumber *sender = dictObj[@"sender"];
    NSLog(@"sender:",sender);
    NSNumber *hasPair = dictObj[@"hasPair"];
    NSLog(@"hasPair:", hasPair);

} else {
    NSLog(@"Failed to parse JSON: %@", [error localizedDescription]);
}

}

输出是这样的。我需要将所有变量(code,serviceId,sender和hasPair)分开。

  2014-07-28 11:46:41.640 Nanny[1445:11303] http://app.ivson.by/?   act=linkinginit&deviceid=1xyhgjs
 2014-07-28 11:46:41.923 Nanny[1445:15b03] ADDRESPONSE - ADDING TO MEMORY ONLY: http://app.ivson.by/?act=linkinginit&deviceid=1xyhgjs
 2014-07-28 11:46:41.924 Nanny[1445:11303] Data from server = {"code":200,"serviceid":"53d60c7cc35f1","sender":1,"hasPair":0}
 2014-07-28 11:46:41.924 Nanny[1445:11303] code:
 2014-07-28 11:46:41.925 Nanny[1445:11303] serviceId:
 2014-07-28 11:46:41.925 Nanny[1445:11303] sender:
 2014-07-28 11:46:41.925 Nanny[1445:11303] hasPair:

谢谢。

1 个答案:

答案 0 :(得分:1)

在NSLog中

,你没有传递参数类型。试试这个

if (obj) {
    NSAssert([obj isKindOfClass:[NSDictionary class]], @"Expected a dictionary");
    NSNumber *code = obj[@"code"];
    NSLog(@"code: %@", code);
    NSString *serviceId = obj[@"serviceID"];
    NSLog(@"serviceId: %@", serviceId);
    NSNumber *sender = obj[@"sender"];
    NSLog(@"sender: %@",sender);
    NSNumber *hasPair = obj[@"hasPair"];
    NSLog(@"hasPair: %@", hasPair);

} else {
    NSLog(@"Failed to parse JSON: %@", [error localizedDescription]);
}