NSJSONSerialization Not Working, NSUTF8StringEncoding Is Working

元气小坏坏 提交于 2019-12-24 05:09:51

问题


I've read the documentation, tutorials, and other Stack Q&A and am hung up on how I'm able to get my JSON to appear using NSUTF8StringEncoding, but not using NSJSONSerialization - which is what I need to extract the data to a NSDictionary or NSArray. I believe it is an issue with the format of the NSData being returned from my URL?

EDIT Here is error: Error Domain=NSCocoaErrorDomain Code=3840 "The operation couldn’t be completed. (Cocoa error 3840.)" (Garbage at end.) UserInfo=0x8aabc30

NSURLRequest *theRequest=[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.sampleURL.com"]
                                          cachePolicy:NSURLRequestUseProtocolCachePolicy
                                      timeoutInterval:15.0];

NSMutableData* responseData = [NSMutableData dataWithCapacity: 0];

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {

    //this works, and have NSLog below
    responseString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    NSLog(@"string %@", responseString);

    [responseData appendData:data];
    responseData = [[NSMutableData alloc] initWithData:data];

     //this is null in NSLog
    NSError * error;
    NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:data   options:NSJSONReadingMutableContainers|NSJSONReadingAllowFragments error:&error];

    NSLog(@"jsonDict dict %@",jsonDict); 
}

Debug Console:

 2014-03-11 07:41:58.233 WBPC[7845:a0b] string   {"id":"a1","session":"General","name":"Exhibitor Setup Begins","startTime":"0900","details":"9am Exhibitor Hall","png":"image","speaker1":"Johnson","speaker2":"Nelson","speaker3":""}{"id":"b1","session":"General","name":"Conference Registration","startTime":"1000","details":"10am Noon Upper Level Lobby","png":"image","speaker1":"Jackson","speaker2":"","speaker3":""}
 2014-03-11 07:41:58.236 WBPC[7845:a0b] jsonDict (null)

回答1:


Your JSON is not well formed. You tell us that it is (white space and line breaks added for legibility purposes):

{
    "id": "a1",
    "session": "General",
    "name": "Exhibitor Setup Begins",
    "startTime": "0900",
    "details": "9am Exhibitor Hall",
    "png": "image",
    "speaker1": "Johnson",
    "speaker2": "Nelson",
    "speaker3": ""
}{
    "id": "b1",
    "session": "General",
    "name": "Conference Registration",
    "startTime": "1000",
    "details": "10am Noon Upper Level Lobby",
    "png": "image",
    "speaker1": "Jackson",
    "speaker2": "",
    "speaker3": ""
}

That's missing a comma between the two dictionary entries, and you're missing the [ and ] that should wrap the JSON. If it's really an array of dictionary entries, it should be:

[
    {
        "id": "a1",
        "session": "General",
        "name": "Exhibitor Setup Begins",
        "startTime": "0900",
        "details": "9am Exhibitor Hall",
        "png": "image",
        "speaker1": "Johnson",
        "speaker2": "Nelson",
        "speaker3": ""
    },
    {
        "id": "b1",
        "session": "General",
        "name": "Conference Registration",
        "startTime": "1000",
        "details": "10am Noon Upper Level Lobby",
        "png": "image",
        "speaker1": "Jackson",
        "speaker2": "",
        "speaker3": ""
    }
]

If you want to check your JSON, you can visit http://jsonlint.com. Also, if you checked the error object returned by JSONObjectWithData, it would have pointed you in the right direction.

You should look how this JSON was generated. It looks like it must have been manually generated. If you were generating this from a PHP page, for example, you should use json_encode, for example, rather than manually generating the JSON.


By the way, you are trying to parse the result in didReceiveData. You shouldn't try to parse until connectionDidFinishLoading. Your didReceiveData should merely append the data to your NSMutableData object. The parsing should be deferred until connectionDidFinishLoading.




回答2:


You're doing it all in the 'didReceiveData' delegate function which isn't the correct place. The only thing that should be there is:

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
    [self.responseData appendData:data];
}

but before this, you should initialise the 'self.responseData' when the connection receives a response:

-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    if(self.responseData != nil) self.responseData = nil;
    self.responseData = [[NSMutableData alloc] init];
}

and then, you need to implement another delegate function called 'connectionDidFinishLoading' and when this method is called, your 'responseData' will contain all of the data from the JSON and will be ready to parse:

-(void)connectionDidFinishLoading:(NSURLConnection *)connection {

     responseString = [[NSString alloc] initWithData:self.responseData encoding:NSUTF8StringEncoding];

     NSLog(@"string %@", responseString);

     NSError * error;
     NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers|NSJSONReadingAllowFragments error:&error];

     NSLog(@"jsonDict dict %@",jsonDict); 
}

I hope that helps in some way.




回答3:


Hi you can try this one.

NSError *error = nil;
NSArray *jsonResponseArray = [NSJSONSerialization JSONObjectWithData: YOURDATA options: NSJSONReadingMutableContainers error: &error];

if (!jsonResponseArray) {
  NSLog(@"Error: %@", error);
} else {
   for(NSDictionary *dic in jsonResponseArray) {
      NSLog(@"dic values are : %@", item);
   }
}

Thanks




回答4:


The JSON string you have posted is not valid JSON. Just because the data is a valid UTF8 string doesn't mean it is necessarily JSON. Try pasting the string from your debugged into JSONLint and it will show you that you're missing a comma between your JSON objects.



来源:https://stackoverflow.com/questions/22326273/nsjsonserialization-not-working-nsutf8stringencoding-is-working

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!