Parsing WordPress REST API post tags

I’m attempting to get the categories and tags related to a WordPress post.

It’s a self-hosted installation with the Jetpack plugin installed and working, so I’m using the WordPress.com Rest API to query.

Read More

Here’s some example JSON which the REST API returns for /posts

You’ll note that the first post returned in the above example (at the time of writing) is tagged facebook, Google, Publicize, Sharing and twitter.

However there’s something of an inconsistency with how the JSON is formatted. Instead of being represented as an array with every object in the array having consistent properties (name, slug, description) – allowing me to simply iterate the array – each tag seems to be represented as its own object, with the object’s name being the name of the tag. Here’s how it shows in the JSON Viewer:

Visualisation of JSON data

So, without knowing the tags in advance, it presents a challenge of how to get the post’s tags.

I’m using .NET 4.5’s HttpClient so I’ve worked around it, of a fashion, using the dynamic type:

public class WordPressBlogPost : IBlogPost
    {
        // IBlogPost implementation
        public DateTime Date { get; set; }
        public DateTime Modified { get; set; }
        public string Title { get; set; }
        public string URL { get; set; }
        public string Content { get; set; }
        public string Excerpt { get; set; }
        public dynamic Tags { get; set; }
        public string Featured_Image { get; set; }
        public int Comment_Count { get; set; }
    }

You can then iterate Tags, were each is a Newtonsoft.Json.Linq.JProperty and access the name, slug, etc. like so:

foreach (var wordpressPost in parseJsonResult.posts)
{
    foreach (var tag in wordpressPost.Tags)
    {
        string tagName = tag.Value.name;
        string tagSlug = tag.Value.slug;
    }
}

However, it feels quite hacky, and I’d like a cleaner way of doing it.

So – does anyone know –

  1. Can I send some sort of querystring parameter or do something else to get it to return a collection?
  2. Is there a nicer way in .NET than using the dynamic type so I can have strongly typed tags?

Related posts

Leave a Reply

1 comment