daniel kilinskas
daniel kilinskas

Reputation: 3558

RestKit key existence in stractured objects

Hello guys,

I want to map my complex JSON structure that pulled from my server with the RestKit.

Here is the JSON structure example:

"_cat0": [
    {
        "title": "category header",
        "catId": 1
    },
    {
        "id": 542232,
        "title": "post post",
        "time": "1421744040"
    },
    {
        "id": 542232,
        "title": "post post",
        "time": "1421744040"
    },
    {
        "id": 542232,
        "title": "post post",
        "time": "1421744040"
    }
],

As you can see here, we have an head object that represents the category of each section. The "_cat0" actually is a prefix that contains the full data of each category in the JSON. This prefix is continuable and contains everything inside, that means: posts, category data and more parameters.

The first object at each category contains the title and the category-id

{
        "title": "category header",
        "catId": 1
    } 

And the other objects contains the posts of the category.

My problem with RestKit is to find the Post object and the Category object by the values in the JSON.

I thought about finding unique key inside the head object and store it as a category object and then any other objects in the JSON stored as a Post. But I didn't found any functions that can help me with the key existence or check if the key of the object is nullable.

Here is my try for this issue:

if ([representation containsValueForKey:@"catId"]) {
        // it's a category object
        return categoryMapping;
    } else {
        // it's a post object
        return postMapping;
    }

But this code crashes after the run.

Any ideas for this issue?

Upvotes: 1

Views: 53

Answers (1)

Ian MacDonald
Ian MacDonald

Reputation: 14030

If you have assigned the JSON array to an object named _cat0, you could do the following:

for (NSDictionary *object in _cat0) {
  if ([[object allKeys] contains:@"catId"]) {
    // Process object as category metadata.
  } else {
    // Process object as a post.
  }
}

If you have control over the JSON response, I strongly recommend that you make its structure more meaningful. Something along the lines of:

"_cat0": {
    "title": "category header",
    "catId": 1
    "posts": [
        {
            "id": 542232,
            "title": "post post",
            "time": "1421744040"
        },
        {
            "id": 542232,
            "title": "post post",
            "time": "1421744040"
        },
        {
            "id": 542232,
            "title": "post post",
            "time": "1421744040"
        }
    ]
},

Upvotes: 1

Related Questions