[英]parsing json in objective C
My json array is like this: 我的json数组是这样的:
[
{
"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). 我的输出应该只是一个带有字符串val的数组,在数组索引0、1和2处的count和sum(顺序无关紧要),并且应该删除重复项(“ val”重复两次)。 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.
我能够消除重复项,但是我不太确定在单独的索引中第三次出现result_names的情况。 Here's my code so far:
到目前为止,这是我的代码:
Above json is stored as: 上面的json存储为:
NSDictionary* json;
NSMutableArray *resultList = [json valueForKey:@"result_names"];
NSArray *res = [[NSSet setWithArray: resultList] allObjects];
Now, NSLog(@"%@", res);
现在,
NSLog(@"%@", res);
gives me: 给我:
(
val
),
(
count,
sum
)
)
Now "res.count" returns 2. I want val, count and sum in different indices. 现在,“ res.count”返回2。我想要val,count和sum在不同的索引中。 Kindly help.
请帮助。
Your -valueForKey:
call is returning an array of arrays, so +setWithArray:
can de-dupe identical arrays but not individual elements. 您的
-valueForKey:
调用返回的是数组数组,因此+setWithArray:
可以对相同的数组进行重复数据删除,但不能对单个元素进行重复数据删除。 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": 您可以使用键值编码集合运算符 “ @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.) (请注意,您的顶级JSON对象是数组,而不是字典。)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.