IOS开发,无法将我的NSData转换为NSJSONSerialization JSONObjectWithData:

时间:2014-11-03 16:53:47

标签: ios nsjsonserialization

以下是我编辑的代码。请帮帮我。我试图在列表视图中显示数据。

     NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];


     NSData *urlData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
     NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url
                                                 cachePolicy:NSURLRequestReturnCacheDataElseLoad
                                             timeoutInterval:30];

     if ([response statusCode] >= 200 && [response statusCode] < 300)
     {
         NSString *responseData = [NSJSONSerialization JSONObjectWithData:urlData
                                                                  options:NSJSONReadingAllowFragments error:&error];
          NSLog(@"responseData : %@", responseData);
         NSArray *entries = [NSJSONSerialization JSONObjectWithData:[responseData dataUsingEncoding:NSUTF8StringEncoding]
                                                            options:0 error:&error];


When I keep a log for NSURL it is navigating to the web service and gives me a result that I need, but the problem arises at responseData

1 个答案:

答案 0 :(得分:-1)

您正在将数据转换为字符串,然后再转换回数据。

只需使用您首先获得的数据......

urlData = [NSURLConnection sendSynchronousRequest:urlRequest
                                returningResponse:&response
                                            error:&error];

if ([response statusCode] >= 200
    && [response statusCode] < 300)
{
    NSArray *entries = [NSJSONSerialization JSONObjectWithData:urlData
                                                       options:NSJSONReadingAllowFragments
                                                         error:&error];

    // do something with the JSON object
}

这应该是你需要做的全部。

修改

好的,这样做并报告它说的内容......

urlData = [NSURLConnection sendSynchronousRequest:urlRequest
                                returningResponse:&response
                                            error:&error];

if ([response statusCode] >= 200
    && [response statusCode] < 300)
{
    NSString *theJSONString = [[NSString alloc] initWithData:urlData encoding:NSUTF8StringEncoding];

    NSLog(@"The JSON is... %@", theJSONString);
}

这至少可以让我们了解究竟会发生什么。