网址正确但字典为空

时间:2013-05-14 07:44:45

标签: ios json

我必须使用JSON下载数据,网址是正确的(在chrome上测试),但我得到一个空字典。我哪里出错了?

  NSLog(@"'url is %@", stringUrl); //correct
  NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:stringUrl]];
  NSHTTPURLResponse __autoreleasing *response = nil;
  NSError __autoreleasing *error = nil;
  NSData *result = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
  // the result is:
  /* <280d0a0d 0a0d0a0d 0a0d0a0d 0a0d0a7b 22636f6d 6d6f6e22 3a7b2261 636b223a 
     224f4b22 2c226661 756c7443 6f646522 3a6e756c 6c2c2266 61756c74 53747269 
     6e67223a 6e756c6c 7d2c2274 6f74616c 223a3138 362c2270 61676522 3a312c22 
      .......*/
  NSString *str = [[NSString alloc] initWithData:result encoding:NSUTF8StringEncoding];
  NSLog(@"  STRING IS %@", str);
  //the string is correct
 SBJsonParser *parser = [[SBJsonParser alloc] init];
 NSLog (@"The parser is %@", parser);
 //The parser is  <SBJsonParser: 0x8877400>
 NSDictionary *object = [parser objectWithData: result];

 NSLog(@" The dictionary is %@", object);// The dictionary is null

字符串的结果:

  NSString *str = [[NSString alloc] initWithData:result encoding:NSUTF8StringEncoding];
  NSLog(@" THE STRING IS %@", str);

  /* ({"common":
{"ack":"OK",
 "faultCode":null,
  "faultString":null},
       "total":8,
        "page":1,
        "limit":15,
         "products":[{"name":"BANANE SOLIDAL BIOLOGICAL  - cartone/estero/2^ 
         cat.",
         "code":"52436",
         "anabel":"264342000",
         "hasPezzature":true,
         "pezzatureList": 
          [{"weight":700.000,"unit":"Gr","formatted":"700GR"}],  
            "disponible":true,
             "promotionImage":null},
         {"name":"KIWI  IT 105-120 II^ VAS
          500GR",
          "code":"52094",
          "anabel":"393261000",
           "hasPezzature":true,
           "pezzatureList":
           [{"weight":500.000,"unit":"GR","formatted":"500GR"}],
              "disponible":true,
              "promotionImage":null},
               ........
               .........]});*/

我把格式设置为可读,实际上返回的数据全部在一行

1 个答案:

答案 0 :(得分:2)

当您尝试在NSDictionary或NSArray中将其强制转换时,在JSON响应的开头和结尾处有一个“(”和“)”,它不会识别它并因此变为空。因此要解析它,你需要添加它:

str = [[str stringByReplacingOccurrencesOfString:@"(" withString:@""] stringByReplacingOccurrencesOfString:@")" withString:@""];

之前

SBJsonParser *parser = [[SBJsonParser alloc] init];
NSLog (@"The parser is %@", parser);
//The parser is  <SBJsonParser: 0x8877400>
NSDictionary *object = [parser objectWithData: result];

NSLog(@" The dictionary is %@", object);// The dictionary is null