1

我必须使用 JSON 下载数据,url 是正确的(在 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},
               ........
               .........]});*/

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

4

1 回答 1

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
于 2013-05-14T09:37:48.247 回答