Softstuff Consulting
My occasional musings of a technical nature
  • Send us a message
  • About Softstuff Consulting
  • Privacy Policy
  • Main Website
C#

Decoding JSON in C#

by Ian Blair February 23, 2019 No Comments

Most people seem to use external libraries when decoding JSON returned from web services or other external functions but in .Net .45 there is a native library that works extremely well for most JSON string returned by external services.

The functions are included in the System.Web.Helpers library and this must be included for this to work, the problem here is that the functions themselves aren’t very well documented but are extremely straightforward to use.

Example 1 A simple JSON string.

{
 id: 12345678,
 id_str:"12345678",
 screen_name:"softstuffc"
}

An example of the code to decode this quickly is

public void test()
{
    string retvalue=MyWebService.Call(); // call your webservice here
    dynamic json=Json.Decode(retvalue);
    long id=json.id;
    string id_str=json.id_str;
    string screenname=json.screen_name;
}

The example above doesn’t have any error trapping or other frills to handle values from the webservice call that may not be JSON strings but not the use of the dynamic keyword in the decode call. The dynamic keyword means the data types are fixed as they aren’t checked and assigned at compile time, but if you attempt to read an element that doesn’t exist or read into a value that isn’t the correct type, for example reading a long value into a string it will throw a runtime error. These can be caught using try{}catch{} statements, and unless you are 100% sure that the data you are reading is complete and correct then I would recommend using them.

Example 2 A simple JSON Array

{ id: 12345678,
    "people":[
    {"firstName":"Bill", "lastName":"Door"},
    {"firstName":"Anna", "lastName":"Jones"},
    {"firstName":"Peter", "lastName":"Piper"}
]}

Code to decode the array

using System.Web.Helpers;
 
public void test()
{
    string retvalue=MyWebService.Call(); // call your webservice here
    dynamic json=Json.Decode(retvalue);
    long id=json.id;
    dynamic people=json.people;
    foreach(dynamic person in people)
    {
        string firstname= person.firstName;
        string lastName=person.lastName
    }
}

In the example above each embedded array in the JSON string is returned as another dynamic object containing an array of more dynamic objects, and it is easy to use a foreach statement to step through and decode each item. This form of recursion can be used to drill down completely into the JSON array for instances where an array might contain more arrays of values.

Example 3 A more complex embedded array

{ id: 12345678,
    "people":[
    {"firstName":"Bill", "lastName":"Door","petsOwned":[{"type":"dog"}{"type":"cat"}]},
    {"firstName":"Anna", "lastName":"Jones"},
    {"firstName":"Peter", "lastName":"Piper","petsOwned":[{"type":"cat"}]}
]}

As this has arrays embedded in an array and example of the code needed to decode this is below

using System.Web.Helpers;
 
public void test()
{
    string retvalue=MyWebService.Call(); // call your webservice here
    dynamic json=Json.Decode(retvalue);
    long id=json.id;
    dynamic people=json.people;
    foreach(dynamic person in people)
    {
        string firstname= person.firstName;
        string lastName=person.lastName
        try // using a try catch as one of the array values does not have an embedded array
        {
            dynamic petsowned=person.petsOwned;
            foreach(dynamic pet in petsowned)
            {
                string type=pet.type;
            }
        }
        catch{}
    }
}

For most decoding situations it works and JSON decoding doesn’t have to involve much manual coding of data structures and classes before you can begin, and has the advantage that when stepping through and debugging the values returned in each dynamic variable are available in the editor.

c#json

  • Previous Updating your CRM V9 connection code4 years ago
  • Next Multithreading in C# to speed up CRM2015 bulk tasks4 years ago

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Recent Posts

  • How to make your Powershell scripts more annoying
  • What motherboard is in my PC
  • A Dynamics365 plugin thought experiment
  • Registering a Dynamics365 plugin and I get an error
  • Going back in time with Dynamics365

Categories

  • Bootstrap
  • C#
  • CSS
  • Dot Net Core
  • Dynamics365
  • JavaScript
  • Powershell
  • T-SQL
  • Thoughts
  • VBScript
  • Visual Studio
  • Windows
  • Xamarin

Recent Comments

  • S0ftStuffB055 on Call a Dynamics365 workflow from JavaScript
  • Siva on Call a Dynamics365 workflow from JavaScript
  • TC Sharpe on Throw exceptions in Dynamics365 workflow plugins, or don’t
  • BigOwl on Throw exceptions in Dynamics365 workflow plugins, or don’t
  • CRMGod on Access a Dynamics365 embedded webresource

Archives

  • January 2021
  • May 2020
  • March 2020
  • February 2020
  • January 2020
  • December 2019
  • October 2019
  • June 2019
  • May 2019
  • February 2019
2023 Softstuff Consulting. Donna Theme powered by WordPress
  • Twitter