Cocoa Error 3840 - NSJSONSerialization

隐身守侯 提交于 2019-11-28 10:35:33

问题


I'm trying to parse a JSON string returned from a ASP.NET web service. The return string has been simplified to just this:

<anyType d1p1:type="q1:string">[{"Firstname":"Johnny"}]</anyType>

When I run the following code in xcode, I get an error of "Error Domain=NSCocoaErrorDomainCode=3840"..."JSON text did not start with array or object and option to allow fragments are not set"

NSURL *url = [NSURL URLWithString:@"http://webserver.com/Service.asmx/GetNames"];
    NSData *data = [NSData dataWithContentsOfURL:url];
      if(data != nil)
        {
            NSError *error = nil;
            id result = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error];
                if(error == nil)
        {
            NSLog(@"%@", result);
        }else{
            NSLog(@"%@",error);
        }
    }else{
        NSLog(@"it's nil");
    }

I'm not really sure what to do here? The error seems to be on the "id result =" line.

*I thought it might be the format of my reutrn string, but everything i read on ASP.NET posts says this is correct.

*I have changed "NSJSONReadingMutableContainers" to be "NSJSONReadingMutableLeves"


回答1:


Is the Web service actually returning the <anyType d1p1:type="q1:string"> and </anyType> portions of that string within the content of the document? If so, that's the problem: The valid JSON string is simply:

[{"Firstname":"Johnny"}],

This is the only content your Web response should contain. Everything in angled brackets is not actually JSON data, and it's throwing the parser off.




回答2:


Try this hope it will work

if ([operation isKindOfClass:[AFJSONRequestOperation class]] && [operation respondsToSelector:@selector(setJSONReadingOptions:)]) {
    ((AFJSONRequestOperation *)operation).JSONReadingOptions = NSJSONReadingAllowFragments;
}
[httpClient enqueueHTTPRequestOperation:operation];


来源:https://stackoverflow.com/questions/9282771/cocoa-error-3840-nsjsonserialization

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