【发布时间】:2016-08-17 03:11:42
【问题描述】:
我有一个 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 会单独返回每个“ingredients”键。
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
【问题讨论】:
标签: ios objective-c arrays json dictionary