JSON获取数据会产生异常

时间:2011-08-25 07:04:41

标签: iphone objective-c json

我正在使用JSON从JSON获取数据,但它提供了异常:

Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** -  [NSCFDictionary objectAtIndex:]: unrecognized selector sent to instance 0x9b1ac50'

SBJsonParser *parser = [[SBJsonParser alloc] init];
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.krsconnect.no/community/api.html?method=event&appid=620&eventid=15946&affecteddate=1310515200000"]];

NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *json_string = [[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding];
NSDictionary *object = [parser objectWithString:json_string error:nil];
appDelegate.books1 = [[NSMutableArray alloc] init];
appDelegate.dates =[[NSMutableArray alloc]init];
appDelegate.descriptionArray=[[NSMutableArray alloc]init];
NSArray *results = [parser objectWithString:json_string error:nil];

for (int i=0; i<[results count]; i++) {
    NSDictionary*dictOne=[results objectAtIndex:i];
    Detail  *aDetail = [[Detail alloc] initWithDictionary:[results objectAtIndex:i]];       
    [appDelegate.descriptionArray addObject:aDetail];
}

3 个答案:

答案 0 :(得分:0)

替换以下行...

    NSDictionary *object = [parser objectWithString:json_string error:nil];

    NSDictionary*dictOne=[results objectAtIndex:i];

跟随一个......

    NSDictionary *object = (NSDictionary*) [parser objectWithString:json_string error:nil];

    NSDictionary *dictOne = (NSDictionary*) [results objectAtIndex:i];

SBJSONParser不支持 objectWithString:error:并提出预编译器警告警告:'SBJsonParser'可能无法响应'-objectWithString:error:',那是为什么会崩溃。

我相应地修改了你的代码,它运行正常。试试吧......

修改后的代码......

    SBJsonParser *parser = [[SBJsonParser alloc] init];
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.krsconnect.no/community/api.html? method = event&appid = 620&eventid = 15946&affecteddate=1310515200000"]];

    NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
    NSString *json_string = [[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding];

    SBJSON *objParser = [[SBJSON alloc] init];
    NSDictionary *object = (NSDictionary *)[objParser objectWithString:json_string error:nil];
    appDelegate.books1 = [[NSMutableArray alloc] init];
    appDelegate.dates =[[NSMutableArray alloc]init];
    appDelegate.descriptionArray=[[NSMutableArray alloc]init];
    NSArray *results = (NSArray *)[objParser objectWithString:json_string error:nil];

    for (int i=0; i<[results count]; i++) {
        NSDictionary*dictOne = (NSDictionary *)[results objectAtIndex:i];
        Detail  *aDetail = [[Detail alloc] initWithDictionary:[results objectAtIndex:i]];       
        [appDelegate.descriptionArray addObject:aDetail];
    }

答案 1 :(得分:0)

    #import <Foundation/Foundation.h>
    #import "SBJsonParser.h"
    #import "SBJsonWriter.h"


    @interface SBJSON : SBJsonBase <SBJsonParser, SBJsonWriter> {

    @private    
        SBJsonParser *jsonParser;
        SBJsonWriter *jsonWriter;
    }


    /// Return the fragment represented by the given string
    - (id)fragmentWithString:(NSString*)jsonrep error:(NSError**)error;

    /// Return the object represented by the given string
    - (id)objectWithString:(NSString*)jsonrep error:(NSError**)error;

    /// Parse the string and return the represented object (or scalar)
    - (id)objectWithString:(id)value allowScalar:(BOOL)x error:(NSError**)error;

    /// Return JSON representation of an array  or dictionary
    - (NSString*)stringWithObject:(id)value error:(NSError**)error;

    /// Return JSON representation of any legal JSON value
    - (NSString*)stringWithFragment:(id)value error:(NSError**)error;

    /// Return JSON representation (or fragment) for the given object
    - (NSString*)stringWithObject:(id)value allowScalar:(BOOL)x error:(NSError**)error;


    @end


    #import "SBJSON.h"

    @implementation SBJSON

    - (id)init {
        self = [super init];
        if (self) {
            jsonWriter = [SBJsonWriter new];
            jsonParser = [SBJsonParser new];
            [self setMaxDepth:512];

        }
        return self;
    }

    - (void)dealloc {
        [jsonWriter release];
        [jsonParser release];
        [super dealloc];
    }

    - (NSString *)stringWithObject:(id)obj {
        NSString *repr = [jsonWriter stringWithObject:obj];
        if (repr)
            return repr;    
        [errorTrace release];
        errorTrace = [[jsonWriter errorTrace] mutableCopy];
        return nil;
    }

    - (NSString*)stringWithObject:(id)value allowScalar:(BOOL)allowScalar error:(NSError**)error {
        NSString *json = allowScalar ? [jsonWriter stringWithFragment:value] : [jsonWriter stringWithObject:value];
        if (json)
            return json;
        [errorTrace release];
        errorTrace = [[jsonWriter errorTrace] mutableCopy];        
        if (error)
            *error = [errorTrace lastObject];
        return nil;
    }

    - (NSString*)stringWithFragment:(id)value error:(NSError**)error {
        return [self stringWithObject:value allowScalar:YES error:error];
    }

    - (NSString*)stringWithObject:(id)value error:(NSError**)error {
        return [self stringWithObject:value
                  allowScalar:NO
                        error:error];
    }

    - (id)objectWithString:(NSString *)repr {
        id obj = [jsonParser objectWithString:repr];
        if (obj)
            return obj;

        [errorTrace release];
        errorTrace = [[jsonParser errorTrace] mutableCopy];

        return nil;
    }


    - (id)objectWithString:(id)value allowScalar:(BOOL)allowScalar error:(NSError**)error {
        id obj = allowScalar ? [jsonParser fragmentWithString:value] : [jsonParser objectWithString:value];
        if (obj)
            return obj;

        [errorTrace release];
        errorTrace = [[jsonParser errorTrace] mutableCopy];
        if (error)
            *error = [errorTrace lastObject];
        return nil;
    }

    - (id)fragmentWithString:(NSString*)repr error:(NSError**)error {
        return [self objectWithString:repr
                  allowScalar:YES
                        error:error];
    }

    - (id)objectWithString:(NSString*)repr error:(NSError**)error {
        return [self objectWithString:repr
                  allowScalar:NO
                        error:error];
    }


    - (NSUInteger)maxDepth {
        return jsonParser.maxDepth;
    }

    - (void)setMaxDepth:(NSUInteger)d {
         jsonWriter.maxDepth = jsonParser.maxDepth = d;
    }

    - (BOOL)humanReadable {
           return jsonWriter.humanReadable;
    }

    - (void)setHumanReadable:(BOOL)x {
        jsonWriter.humanReadable = x;
    }

    - (BOOL)sortKeys {
        return jsonWriter.sortKeys;
    }

    - (void)setSortKeys:(BOOL)x {
        jsonWriter.sortKeys = x;
    }

    @end

答案 2 :(得分:0)

答案其实非常简单,它就在错误信息中。您正在尝试将NSDictionary视为NSArray。您这样做的原因是您的HTTP请求返回JSON 对象,而不是JSON 数组。就是这样:

{
    "affectedDate": 1310515200000,
    "category": "Sport",
    "content": "Kl 2100 hver tredje lørdag i måneden arrangerer <<<SNIP>>>",
    "eventId": 15946,
    "image": "http://shelf-media.s3.amazonaws.com/39be3cbc5584eb0e9f61c9926a62d478_gmedium.jpg",
    "latitude": "58.1441382",
    "longitude": "7.9933589",
    "title": "HARVEY'S SATURDAY NIGHT FOOTBALL QUIZ"
}

看,不是数组。我怀疑你正在解析相同的JSON字符串两次意味着你想要另一个HTTP请求来获取另一个字符串,但是你不小心将它从代码中删除了。

请注意,这是基本的输入验证。你需要检查a)你的JSON字符串是否被正确解析了b)你得到了你期望的结构。仅仅因为外部服务昨天给你一个JSON数组并不意味着它今天会这样做,如果服务的所有者改变它。

相关问题