Home > C# > C# | Parse Json using System.Text.Json (instead of Json.NET)

C# | Parse Json using System.Text.Json (instead of Json.NET)

In this post lets see how to parse a complex Json content without using Json.NET library and by using the native System.Text.Json namespace.

What and why cant I use Json.NET library?

  • Json.NET (also known as Newtonsoft.Json) is a popular third-party JSON library for .NET.
  • Flexible Serialization, Better Performance, LINQ to JSON, JSON Path, and JSON Schema validation are some of the standout features of Json.NET library.
  • I was unable to utilize the Json.NET library solely due to the fact that it is a third-party tool, and we are obligated not to use it.

Scenario:

Coming to our scenario we have following json content and we need to parse and read the inputs and outputs collection from the actions array.

{
  "actions": [
    {
      "name": "Display select file dialog",
      "status": "Failed",
      "inputs": {
        "allowMultiple": {
          "localizedName": "Allow multiple selection",
          "value": "False",
          "variableName": ""
        },
        "title": {
          "localizedName": "Dialog title",
          "value": "Select the excel file to extract table from...",
          "variableName": ""
        }
      },
      "outputs": {
        "selectedFile": {
          "localizedName": "Selected file",
          "value": "",
          "variableName": "SelectedFile"
        },
        "buttonPressed": {
          "localizedName": "Button pressed",
          "value": "Cancel",
          "variableName": "ButtonPressed"
        }
      }
    },
    {
      "name": "If",
      "status": "Succeeded",
      "inputs": {
        "expression": {
          "localizedName": "Condition",
          "value": "False",
          "variableName": ""
        }
      },
      "outputs": {}
    }
  ],
  "childFlowsLogStatus": "Default"
}

C# Code Snippet:

Following is the C# code snippet , which parses the json content and flattens the inputs and outputs collection json using native System.Text.Json namespace.

using System;
using System.Text;
using System.Text.Json;

namespace ParseJson
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                var jsonContent = "{\"actions\":[{\"name\":\"Display select file dialog\",\"status\":\"Failed\",\"inputs\":{\"allowMultiple\":{\"localizedName\":\"Allow multiple selection\",\"value\":\"False\",\"variableName\":\"\"},\"title\":{\"localizedName\":\"Dialog title\",\"value\":\"Select the excel file to extract table from...\",\"variableName\":\"\"}},\"outputs\":{\"selectedFile\":{\"localizedName\":\"Selected file\",\"value\":\"\",\"variableName\":\"SelectedFile\"},\"buttonPressed\":{\"localizedName\":\"Button pressed\",\"value\":\"Cancel\",\"variableName\":\"ButtonPressed\"}}},{\"name\":\"If\",\"status\":\"Succeeded\",\"inputs\":{\"expression\":{\"localizedName\":\"Condition\",\"value\":\"False\",\"variableName\":\"\"}},\"outputs\":{}}],\"childFlowsLogStatus\":\"Default\"}";

                string strInputXML = ParseInputandOutput(jsonContent, "inputs");
                string strOutputXML = ParseInputandOutput(jsonContent, "outputs");
                Console.WriteLine($"Input content : {strInputXML}");
                Console.WriteLine($"Output content : {strOutputXML}");
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Error {ex.Message}");
            }
            finally
            {
                Console.ReadLine();
            }
        }

        private static string ParseInputandOutput(string flowContextDetails, string propertyName)
        {
            StringBuilder sbrRawText = new StringBuilder();
            JsonDocument doc = JsonDocument.Parse(flowContextDetails);
            JsonElement actions = doc.RootElement.GetProperty("actions");

            foreach (JsonElement action in actions.EnumerateArray())
            {
                if (action.GetProperty("status").GetString() == "Failed")
                {
                    JsonElement propertyNodes = action.GetProperty(propertyName);
                    sbrRawText.AppendLine(propertyNodes.ToString());
                }
            }

            return sbrRawText.ToString();
        }
    }
}

Run the console app and you will get the flattened json of inputs and outputs collection.

Hope this blog post gives the idea of how to parse json using native System.Text.Json namespace.

Advertisement
Categories: C# Tags:
  1. No comments yet.
  1. No trackbacks yet.

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 )

Facebook photo

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

Connecting to %s

%d bloggers like this: