简体   繁体   中英

parsing json in objective C

My json array is like this:

[
    {
        "result_names": [
            "val"
        ]
    },
    {
        "result_names": [
            "val"
        ]
    },
    {
     "result_names": [
            "count",
            "sum"
        ]
    }
]

My output should just be an array with string val, count and sum at array indices 0, 1 and 2 (order doesn't matter) and duplicates should be removed ("val" is repeated twice). I am able to get rid of the duplicates but I am not quite sure to get the third occurrence of result_names at separate indices. Here's my code so far:

Above json is stored as:

NSDictionary* json;
NSMutableArray *resultList = [json valueForKey:@"result_names"];
NSArray *res = [[NSSet setWithArray: resultList] allObjects];

Now, NSLog(@"%@", res); gives me:

        (
        val
    ),
        (
        count,
        sum
    )
)

Now "res.count" returns 2. I want val, count and sum in different indices. Kindly help.

Your -valueForKey: call is returning an array of arrays, so +setWithArray: can de-dupe identical arrays but not individual elements. You'll have to do something like this:

NSArray *resultLists = [json valueForKey:@"result_names"];
NSMutableSet *results = [NSMutableSet set];
for (NSArray *resultList in resultLists) {
    [results addObjectsFromArray:resultList];
}

You can use the Key-Value Coding collection operator "@distinctUnionOfArrays":

NSArray *json = @[
                        @{@ "result_names": @[@"val"]},
                        @{@ "result_names": @[@"val"]},
                        @{@ "result_names": @[@"sum", @"count"]},
                        ];

NSArray *res = [json valueForKeyPath:@"@distinctUnionOfArrays.result_names"];
NSLog(@"%@", res);

Output:

(
    val,
    count,
    sum
)

(Note that your top-level JSON object is an array, not a dictionary.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM