gdubs
gdubs

Reputation: 2754

ios parse jsonresult how to iterate if it's not a dictionary?

I have this issue when I'm trying to parse my jsonresult that comes from a webapi. Take note, that whenver it would return a json result that looks like this:

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

This code works on that result:

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"];

            }
        }
    }

But once it returns a none list result that looks like so:

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

It would not go through the

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

Now if I take it out and just let it go straight to the assignment of the properties. The "item" variable that is returned from the jsonarray is the key eg: Id, Name, etc. Now I'm not sure how to properly iterate through the thing and assign it using keys. It seems like it's using indexes? Do I make another dictionary?

Upvotes: 0

Views: 605

Answers (1)

Dipen Panchasara
Dipen Panchasara

Reputation: 13600

Its quite simple to get the solution of it, when you are unaware about the result DataType simply TypeCast your object to id (A Generic DataType)

Store your json Response in 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"];
}

Your response is Dictionary when you have only 1 Record in Result, and when you have more then 1 Record it will be an Array.

Upvotes: 1

Related Questions