寻找有关如何有效分裂我的json的指导

时间:2014-04-04 21:35:08

标签: objective-c json ios7 split

所以我理解如何拆分包含JSON信息的数组,但我坚持的是试图让它只显示第一个空格的所有内容。例如,如果您查看JSON站点(http://iam.colum.edu/portfolio/api/course?json=True),每个课程的开头都有一个课程编号。我想拆分每个只显示课程名称的数组对象。例如,如果你看一下网站,第一个对象是“计算机体系结构”,第二个是“数字图像和设计”......等等。我不需要知道如何分割字符串,我已经可以这样做了,但是如何分割它以便它带走“xx-xxx”(x是课程编号)?我目前在每个空格处拆分的代码,但由于显而易见的原因,这些代码无法正常工作。

JSONViewController

    dispatch_async(progressQueue, ^{
                jstring = [JSONHelper JSONgetString:@"http://iam.colum.edu/portfolio/api/course?json=True"];
            dispatch_async(dispatch_get_main_queue(), ^{
                //main thread code
                //textView.text = jstring;
                jarray = [jstring componentsSeparatedByString:@" "];
                textView.text = [jarray objectAtIndex:1];
 NSString * fullString = [NSString string];
            for(int i = 0; i < jarray.count; i++)
            {
                fullString = [fullString stringByAppendingString:[jarray objectAtIndex:i]];
            }
            textView.text = fullString;

            NSError *error = nil;
            NSArray * resultArray = [NSJSONSerialization JSONObjectWithData: [jstring dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingMutableContainers                                                                      error: &error];

            if ( !resultArray ) {
                NSLog(@"Error parsing JSON: %@", error);
            } else {
                for(NSString * course in resultArray) {
                    NSLog(@"Course: %@", course);
                }
            }

JSONHelper.h

@interface JSONHelper : NSObject

+ (NSDictionary *)JSONget:(NSString *)query;
+ (NSString *)JSONgetString:(NSString *)query;
+ (NSString *)JSONpostString:(NSString *)query;
+(NSString *)JSONpostString:(NSString *)query
                   withData:(NSString *)jsonData;
@end

JSONHelper.m

@implementation JSONHelper


//returns a dictionar from a get request
+ (NSDictionary *)JSONget:(NSString *)query
{
    NSData *jsonData = [[NSString stringWithContentsOfURL:[NSURL URLWithString:query] encoding:NSUTF8StringEncoding error:nil] dataUsingEncoding:NSUTF8StringEncoding];
    NSError *error = nil;
    NSDictionary *results = jsonData ? [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:&error] : nil;
    if (error) NSLog(@"[%@ %@] JSON error: %@", NSStringFromClass([self class]), NSStringFromSelector(_cmd), error.localizedDescription);
    return results;
}

//returns JSON string from get request
+(NSString *)JSONgetString:(NSString *)query
{

    NSString* searchURL = [NSString stringWithFormat:query];

    NSError* error = nil;               //error for NSUSRLConnection
    NSURLResponse* response = nil;
    NSMutableURLRequest* request = [[NSMutableURLRequest alloc] init];

    NSURL* URL = [NSURL URLWithString:searchURL];
    [request setURL:URL];
    [request setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData];
    [request setTimeoutInterval:30];

    NSData* data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];

    if (error)
    {
        NSLog(@"Error performing request %@", searchURL);
        return 0;
    }

    NSString *jsonString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    NSLog(@"jsonString:%@", jsonString);
    return jsonString;
}

+(NSString *)JSONpostString:(NSString *)query{
    NSString* searchURL = [NSString stringWithFormat:query];

    NSError* error = nil;
    NSURLResponse* response = nil;
    NSMutableURLRequest* request = [[NSMutableURLRequest alloc] init];

    NSURL* URL = [NSURL URLWithString:searchURL];
    [request addValue: @"application/json" forHTTPHeaderField:@"Accept"];
    [request addValue: @"application/json" forHTTPHeaderField:@"Content-Type"];
    [request setHTTPMethod:@"POST"];
    [request setURL:URL];
    [request setTimeoutInterval:15];

    NSData* data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];

    if (error)
    {
        NSLog(@"Error performing request %@", searchURL);
        return 0;
    }

    NSString *jsonString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    NSLog(@"jsonString:%@", jsonString);
    return jsonString;
}

+(NSString *)JSONpostString:(NSString *)query
                   withData:(NSString *)jsonData
{
    NSString* searchURL = [NSString stringWithFormat:query];

    NSError* error = nil;
    NSURLResponse* response = nil;
    NSMutableURLRequest* request = [[NSMutableURLRequest alloc] init];

    NSURL* URL = [NSURL URLWithString:searchURL];
    [request addValue: @"application/json" forHTTPHeaderField:@"Accept"];
    [request addValue: @"application/json" forHTTPHeaderField:@"Content-Type"];

    [request setHTTPMethod:@"POST"];
    [request setURL:URL];

    [request setTimeoutInterval:30];
    NSData* requestData = [jsonData dataUsingEncoding:NSUTF8StringEncoding];
    [request addValue:[NSString stringWithFormat:@"%d", [requestData length]] forHTTPHeaderField:@"Content-Length"];
    [request setHTTPBody:requestData];

    NSData* data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];

    if (error)
    {
        NSLog(@"Error performing request %@", searchURL);
        return 0;
    }

    NSString *jsonString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    NSLog(@"jsonString:%@", jsonString);
    return jsonString;
}


@end

1 个答案:

答案 0 :(得分:0)

NSDictionary *dictionary = [JSONHelper JSONget:@"http://iam.colum.edu/portfolio/api/course?json=True"];

    for (id course in dictionary) {
        NSLog(@"%@", [course substringFromIndex:8]);
    }

正如你所看到的那样,所有这些课程编号都有相同的模式(所以我认为不会改变)和它的xx-xxxx(此后7个字符+空格)。在那个cas中你可以很容易地使用索引8中的子串(从0开始计算)。


如果您仍然渴望如何执行此操作,以防这些课程编号可能有不同的长度,您可以尝试使用此解决方案:

NSDictionary *dictionary = [JSONHelper JSONget:@"http://iam.colum.edu/portfolio/api/course?json=True"];

    for (id course in dictionary) {
        NSArray *courseArray = [course componentsSeparatedByString:@" "];
        NSMutableString *courseName = [NSMutableString string];
        for (int i = 1; i < [courseArray count] ; i++) {
            [courseName appendFormat:@"%@ ", courseArray[i]];
        }

        // Deleting last character which is whitespace
        [courseName substringToIndex:courseName.length -1];

        NSLog(@"%@", courseName);
        [courseName setString:@""];
    }

它可能不是处理问题最有效的方法,但它只是有效!