All Articles

Flatten json object to send within an Azure Hub Notification Template

Have you ever needed to flatten your json to a bunch of properties? If yes, continue to read.

When we need to send a notification to an Azure Notification Hub , we can choose from sending a native notification to Windows, Windows Phone, Apple or Google, or alternatively, use the agnostic method which uses templates.

Currently, I am using the template approach, and here is the method signature

public Task<NotificationOutcome> SendTemplateNotificationAsync(IDictionary<string, string> properties);

So, basically we are only allowed to send key value properties. 

Let's say that I have a string representing a json object, and I want to send it using this method. To do this, I need to flatten my json (which can have nested objects and arrays inside it) and get a dictionary with all the keys.

Here is an example of json object

{
	"name": "Bruno",
	"surName": "Camara",
	"address": {
		"street": "My Street",
		"number": 53
		"zipCode": "2840-344"
	},
	"familyMembers": [
		{ "name": "Filipa", relation: "wife" },
		{ "name": "Dekas", relation: "son" },
		{ "name": "Pipo", relation: "son" },		
	]	
}

I want to transform this in a dictionary with the following set of key:value

name:Bruno
surName:Camara
address.street:My Street
address.number:53
address.zipCode:2840-344
familyMembers[0].name: Filipa
familyMembers[0].relation: wife
familyMembers[1].name: Dekas
familyMembers[1].relation: son
familyMembers[2].name: Pipo
familyMembers[2].relation: son

Using the library Json.NET with Linq, it's something that we can do it relatively easy

private static Dictionary<string, string> GetNotificationPropertiesFromMessageContent(string messageContent)
{
	JObject jobject = JObject.Parse(messageContent);

	return jobject.Descendants()
		.Where(j => j.Children().Count() == 0)
		.Aggregate(
			new Dictionary<string, string>(),
			(props, jtoken) =>;
			{
				props.Add(jtoken.Path, jtoken.ToString());
				return props;
			});
}

Basically we are querying for all nodes that are leafs, and in that case we add its path and value to the dictionary.

Here is a console application

image

And here is the result of running it

image

I hope it helps.