我有个问题。
我正在使用XMLReader类来获得NSDictionary
,一切都很好。但我无法获得productData元素的矩阵值。
具体来说,我有以下NSDictionary
:
{
response = {
products = {
productsData = (
{
alias = "Product 1";
id = 01;
price = "10";
},
{
alias = "Product 2";
id = 02;
price = "20";
},
{
alias = "Product 3";
id = 03;
price = "30";
});
};
};
}
我用这个代码创建了deNSDictionary
:
NSDictionary *dictionary = [XMLReader dictionaryForXMLData:responseData error:&parseError];
和responseData包含:
<application>
<products>
<productData>
<id>01</id>
<price>10</price>
<alias>Product 1</alias>
</productData>
<productData>
<id>02</id>
<price>20</price>
<alias>Product 2</alias>
</productData>
<productData>
<id>02</id>
<price>20</price>
<alias>Product 3</alias>
</productData>
</products>
</application>
然后,我不知道如何获取每个productData的值,比如id、price和alias。。。
有人知道怎么做吗??
谢谢,请原谅我英语不好!
NSArray* keys = [theDict allKeys];
for(NSString* key in keys) {
id obj = [theDict objectForKey:key];
// do what needed with obj
}
你可以试试这样的东西:
NSArray* keys = [theDict allKeys];
for(NSString* key in keys) {
if ([key isEqualToString:@"product"]) {
NSArray* arr = [theDict objectForKey:key];
// do what needed with arr
}
}
NSDictionary
--allValues
上有一个方法,它返回一个包含字典值的新数组。也许这会有所帮助。
从开始
NSDictionary *dictionary = [XMLReader dictionaryForXMLData:responseData error:&parseError];
你可以这样做:
NSDictionary *application = [dictionary objectForKey:@"application"];
if ([[application objectForKey:@"products"] isKindOfClass [NSArray class]]) {
NSArray *products = [application objectForKey:@"products"];
for (NSDictionary *aProduct in products) {
// do something with the contents of the aProduct dictionary
}
else if {[[application objectForKey:@"products"] isKindOfClass [NSDictionary class]]) {
// you will have to see what the returned results look like if there is only one product
// that is not in an array, but something along these lines may be necessary
// to get to a single product dictionary that is returned
}
我遇到过类似的情况(解析JSON(,其中没有为signle值返回数组,因此必须检查结果是否为数组(在您的情况下为产品字典(或单个NSDictionary(在您情况下为商品字典(。