Azure.Storage.Queues QueueMessage Deserialize JSON with .NET Core

The documentation around .NET QueueMessage is a little fuzzy so depending on the version of your NuGet libraries might differ in properties. This article uses the Azure.Storage.Queues, Version=12.7.0.0.

If you, like me, have systems writing JSON messages to the queue, you also struggle with converting these queue messages back to an object when reading from the queue.

But with a little help from NewtonSoft, it does not have to be that difficult.

Imagine that you wish to get this simple message from the queue:

A simple JSON message added to the queue via Visual Studio

This message can be mapped to this class:

using Newtonsoft.Json;

namespace MyCode
{
  public class HelloWorld
  {
    [JsonProperty("title")]
    public string Title { get; set; }

    [JsonProperty("text")]
    public string Text { get; set; }
  }
}

CHALLENGE #1: IS THE CONTENT ENCODED?

Now, when you read the message from the queue, you might get a surprise, as the original message is nowhere to be seen:

The message in the MessageText property?

Yes, when adding messages from Visual Studio, the contents is base 64 encoded. So first the message needs to be decoded, and then converted into an object.

THE EXTENSION METHOD:

This extension method will do the heavy lifting for you:

using Azure.Storage.Queues.Models;
using Newtonsoft.Json;
using System;
using System.Text;

namespace MyCode
{
  public static class QueueMessageExtensions
  {
    public static string AsString(this QueueMessage message)
    {
      byte[] data = Convert.FromBase64String(message.MessageText);
      return Encoding.UTF8.GetString(data);
    }

    public static T As<T>(this QueueMessage message) where T : class
    {
      byte[] data = Convert.FromBase64String(message.MessageText);
      string json = Encoding.UTF8.GetString(data);
      return Deserialize<T>(json, true);
    }

    private static T Deserialize<T>(string json, bool ignoreMissingMembersInObject) where T : class
    {
      T deserializedObject;
      MissingMemberHandling missingMemberHandling = MissingMemberHandling.Error;
      if (ignoreMissingMembersInObject)
        missingMemberHandling = MissingMemberHandling.Ignore;
      deserializedObject = JsonConvert.DeserializeObject<T>(json, new JsonSerializerSettings { MissingMemberHandling = missingMemberHandling, });
      return deserializedObject;
    }

  }
}

USAGE:

// This is an arbitrary class that returns a list of messages from 
// an Azure Queue. You have your own class here
IEnumerable<QueueMessage> messages = await _queueRepository.Get();

foreach (var message in messages)
{
  // Use the extension method to convert the message to the
  // HelloWorld type:
  var obj = message.As<HelloWorld>();
  // You can now access the properties:
  _logger.LogInformation($"{obj.Title}, {obj.Text}");
}

MORE TO READ:

About briancaos

Developer at Pentia A/S since 2003. Have developed Web Applications using Sitecore Since Sitecore 4.1.
This entry was posted in .net, .NET Core, c#, General .NET, Microsoft Azure and tagged , , , , , . Bookmark the permalink.

1 Response to Azure.Storage.Queues QueueMessage Deserialize JSON with .NET Core

  1. Pingback: Read from Azure Queue with .NET Core | Brian Pedersen's Sitecore and .NET Blog

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.