开发者

How to return a raw string of text/json from aspnet mvc and parse it with the iPhone JSON library

I have a web service that returns a raw string of JSON data (sample below)

{'d':{'success':true,'msg':null,'data':[{'productId':'4b7fcb0f818e4a4abaf5b3c78654b631','id':4283}]}}

... And when I attempt to parse this JSON using the popular JSON library for iPhone development I notice a problem in the following method

- (id)objectWithString:(NSString *)repr {
    [self clearErrorTrace];

    if (!repr) {
        [self addErrorWithCode:EINPUT description:@"Input was 'nil'"];
        return nil;
    }

    depth = 0;
    c = [repr UTF8String];

    id o;
    if (![self scanValue:&o]) {
        return nil;
    }
// more code ...
}

When I hit the last if statement shown I show c to be a valid char (showing the json values inside as expected) but I notice that after o is defined I return nil inside that last if causing this error from the library

#import "NSString+SBJSON.h"
#import "SBJsonParser.h"

@implementation NSString (NSString_SBJSON)

- (id)JSONValue
{
    SBJsonParser *jsonParser = [SBJsonParser new];
    id repr = [jsonParser objectWithString:self];
    if (!repr)
        NSLog(@"-JSONValue failed. Error trace is: %@", [jsonParser errorTrace]);
    [jsonParser release];
    return repr;
}

@end

Any idea what might be wrong with taking a string of what looks like json and trying to parse it like the below?

- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
    [connection release];开发者_开发问答

    NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
    [responseData release];

    NSArray *json = [responseString JSONValue]; //here it all fails
}

Just as a note- this works without error when I query a valid json web service from a large company. My app is aspnet mvc and the return line is simply

return this.Content(jsonStringValue, "text/json");


You should use the built in JSON result object from your action method instead of the Content() method:

return Json(data);

It will automatically serialize your object to be valid JSON.


It would be useful to provide actual error messages/traces.

At any rate, your JSON string is not valid: a string in JSON is quoted within double quotes, not single quotes. The following is valid JSON:

{"d":{"success":true,"msg":null,"data":[{"productId":"4b7fcb0f818e4a4abaf5b3c78654b631","id":4283}]}}

Edit: note that your JSON (top level) data represents an object, not an array. Hence

NSArray *json = [responseString JSONValue];

should be replaced with

NSDictionary *json = [responseString JSONValue];

because SBJSON represents JSON objects as dictionaries.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜