0

当我尝试解析来自 webapi 的 jsonresult 时,我遇到了这个问题。请注意,无论何时它都会返回如下所示的 json 结果:

[{"Id":0, "Name":Wombat, "Category":Animal}, 
{"Id":1, "Name":Trident, "Category":Object}]

此代码适用于该结果:

NSArray *jsonresult = [WCFServiceRequest processWebApiGETRequestWithURL:url];

    if(jsonresult){
        for(id item in jsonresult){

            NSLog(@"item is %@", item);


            if([item isKindOfClass:[NSDictionary class]]){
                object.Id = [item objectForKey:@"Id"];
                object.name = [item objectForKey:@"Name"];
                object.category = [item objectForKey:@"Category"];

            }
        }
    }

但是一旦它返回一个看起来像这样的无列表结果:

{"Id":1, "Name":Trident, "Category":Object}

它不会通过

if([item isKindOfClass:[NSDictionary class]]){

现在,如果我把它拿出来,让它直接分配属性。从 jsonarray 返回的“item”变量是键,例如:Id、Name 等。现在我不确定如何正确地遍历该事物并使用键分配它。似乎它正在使用索引?我要制作另一本词典吗?

4

1 回答 1

1

当您不知道结果DataType只是TypeCast您的对象id(A Generic DataType)时,获得它的解决方案非常简单

将您的 json 响应存储在id

id jsonresult = [WCFServiceRequest processWebApiGETRequestWithURL:url];

// Check whether Response is An Array of Dictionary
if([jsonresult isKindOfClass:[NSArray class]])
{
    NSLog(@"it has multiple Dictionary so iterate through list");
    if(jsonresult){
        for(id item in jsonresult){
            NSLog(@"item is %@", item);                                
            if([item isKindOfClass:[NSDictionary class]]){
                object.Id = jsonresult[@"Id"];
                object.name = jsonresult[@"Name"];
                object.category = jsonresult[@"Category"];                    
            }
        }
    }
}
// Its Dictionary
else if([jsonresult isKindOfClass:[NSDictionary class]])
{
    NSLog(@"It has only one dictionary so simply read it");
    object.Id = jsonresult[@"Id"];
    object.name = jsonresult[@"Name"];
    object.category = jsonresult[@"Category"];
}

您的响应是Dictionary当您在 Result 中只有 1 条记录时,当您有超过 1 条记录时,它将是一个Array.

于 2013-04-26T06:54:29.717 回答