开发者

how to parse array of objects using json for iphone

I have a problem parsing the array of objects from the JSON result.

[
    {
        "first_name":"vijay",
        "last_name":"last",
        "creditCardNumber":"178978977779787979",
        "month":"02","year":"2012",
        "address":"Addres2"
    }

    { 
        "first_name":"vijay",
        "last_name":"last",
        "creditCardNumber":"178978977779787979",
        "month":"02","year":"2012",
        "address":"Addres2"
    }

 开发者_开发百科   {
        "first_name":"vijay",
        "last_name":"last",
        "creditCardNumber":"178978977779787979",
        "month":"02","year":"2012",
        "address":"Addres2"
    }
]

I wish to extract creditCardNumber value from all objects in the array.


Google "JSON Framework". Follow the (easy) instructions to install it.

Then go:

//let's say there's NSString *jsonString.

NSArray *userData = [jsonString JSONValue];

NSMutableArray *creditCards = [NSMutableArray array];
for (NSDictionary *user in userData) {
    [creditCards addObject:[user objectForKey:@"creditCardNumber"]];
}

You'll drop out the bottom of that with NSMutableArray *creditCards full of NSString objects containing the credit card numbers.


@Dan Ray answer is correct, but if you want to avoid third-party librairies you can use NSJSONSerialization:

Assuming that NSData *responseData is containing your JSON.

NSArray *userData = [NSJSONSerialization JSONObjectWithData:responseData options:NSJSONReadingAllowFragments error:nil];

NSMutableArray *creditCards = [NSMutableArray array];
for (NSDictionary *user in userData) {
    [creditCards addObject:[user objectForKey:@"creditCardNumber"]];
}

Source: NSJSONSerialization.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜