将所有键值组合到一个NSMutable Array中

时间:2016-08-17 03:11:43

标签: ios objective-c arrays json dictionary

我有一个JSON文件:

{
      "locations": [

    { "ingredients" : "Biscuits\n3 cups All-purpose Flour\n2 Tablespoons Baking Powder\n1/2 teaspoon Salt\nShortened for example” },

    { "ingredients" : "12 whole Dinner Rolls Or Small Sandwich Buns (I Used Whole Wheat)\n1 pound Thinly Shaved Roast Beef Or Ham (or Both!)\nShortened for example” },  
    //many more records.  only included 2 for example                            
      ]
    }

我将“ingredients”键变成了一个带有下面代码的数组,但是NSLog将每个“components”键分开。

NSLog示例:

(饼干

面粉),

(罗尔斯

牛肉)

这样就可以了,但它会阻止我按字母顺序排序所有成分值,并阻止我删除所有“成分”词典中的所有重复值。我不控制JSON文件,因此无法手动组合它们。 任何人都可以推荐正确的代码,将所有“成分”键值合并为一个吗?

期望的结果示例:

(饼干

面粉

罗尔斯

牛肉)

@implementation JSONLoaderIngreds

- (NSArray *)ingredientsFromJSONFile:(NSURL *)url {
    // Create a NSURLRequest with the given URL
    NSURLRequest *request = [NSURLRequest requestWithURL:url
                                             cachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData
                                         timeoutInterval:30.0];

    // Get the data
    NSURLResponse *response;
    NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response  error:nil];

    // NSData *jsonData = [NSJSONSerialization dataWithJSONObject:arr options:NSJSONWritingPrettyPrinted error:&error];


    // Now create a NSDictionary from the JSON data
    NSDictionary *jsonDictionary = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];

    // Create a new array to hold the locations
    NSMutableArray *locations = [[NSMutableArray alloc] init];

    // Get an array of dictionaries with the key "locations"
    NSMutableArray *array = [jsonDictionary objectForKey:@"locations"];

 for(NSDictionary *dict in array) {

        NSString *string = [dict objectForKey:@"ingredients"];
        NSMutableString *removewords = [string mutableCopy];
        CFStringTrimWhitespace((__bridge CFMutableStringRef) remove words);


//\\//\\//\\//\\//\\EDIT Added Code Below//\\//\\//\\//\\//\\//\\

[removewords replaceOccurrencesOfString:@"[0-9]" withString:@"" options:NSRegularExpressionSearch range:NSMakeRange(0, [removewords length])];
        [removewords replaceOccurrencesOfString:@"tablespoons " withString:@"" options:1 range:NSMakeRange(0, [removewords length])];
        [removewords replaceOccurrencesOfString:@"cups " withString:@"" options:1 range:NSMakeRange(0, [removewords length])];
        [removewords replaceOccurrencesOfString:@"cup " withString:@"" options:1 range:NSMakeRange(0, [removewords length])];

//\\//\\//\\//\\//\\EDIT Added Code Above//\\//\\//\\//\\//\\//\\


 NSArray *brokenIntoParts = [removewords componentsSeparatedByString:@"\n"];
        NSArray *sortedArray = [brokenIntoParts sortedArrayUsingSelector:@selector(localizedCaseInsensitiveCompare:)];
        for (NSString *ingredient in sortedArray) {
            [locations addObject:ingredient];
        }
        NSLog(@"%@", sortedArray);
    }
return locations;
}


@end

1 个答案:

答案 0 :(得分:0)

嘿根据我的理解,我已经简化了您的数据成分所有序列化后您想要的内容如下所述:

@implementation JSONLoaderIngreds

- (NSArray *)ingredientsFromJSONFile:(NSURL *)url {
    // Create a NSURLRequest with the given URL
    NSURLRequest *request = [NSURLRequest requestWithURL:url
                                             cachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData
                                         timeoutInterval:30.0];

    // Get the data
    NSURLResponse *response;
    NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response  error:nil];

    // NSData *jsonData = [NSJSONSerialization dataWithJSONObject:arr options:NSJSONWritingPrettyPrinted error:&error];


    // Now create a NSDictionary from the JSON data
    NSDictionary *jsonDictionary = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];

    // Create a new array to hold the locations
    NSMutableArray *locations = [[NSMutableArray alloc] init];

    //Replaced Code with sort irritation

    for(NSString *ingredientsStr in [[jsonDictionary objectForKey:@"locations"] valueForKey:@"ingredients"]){
        [locations addObjectsFromArray:[ingredientsStr componentsSeparatedByString:@"\n"]];
    }


    return locations;
}

在此代码上方运行后,您将获得单个数组中所有成分数据的输出。

(
    Biscuits,
    "3 cups All-purpose Flour",
    "2 Tablespoons Baking Powder",
    "1/2 teaspoon Salt",
    "Shortened for example",
    "12 whole Dinner Rolls Or Small Sandwich Buns (I Used Whole Wheat)",
    "1 pound Thinly Shaved Roast Beef Or Ham (or Both!)",
    "Shortened for example"
)

希望这会对你有所帮助。

相关问题