【问题标题】:Combine all key values into one NSMutable Array将所有键值组合成一个 NSMutableArray
【发布时间】: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


    【解决方案1】:

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

    @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;
    }
    

    在上面运行此代码后,您将得到下面的输出,其中包含单个数组中的所有 ingredients 数据。

    (
        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"
    )
    

    希望这会对你有所帮助。

    【讨论】:

    • 如果以上答案解决了您的问题,请接受。
    • 感谢您的回复。今晚会试试,让你知道它是如何工作的。
    • 我无法让它工作,但不是你的错,因为我意识到并非所有代码都正确粘贴在原始问题中。我编辑了问题并添加了替换OccurrencesOfString 的缺失代码。我如何在不丢失此功能的情况下实现您的代码?你能用你建议的方式更新你的答案吗?再次感谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-09
    • 2017-07-14
    • 1970-01-01
    相关资源
    最近更新 更多