[C# Tutorials] How to quickly parse JSON data in C#

catgirl

Administrator
Staff member
Administrator
May 28, 2020
155
28
22
United States
envyforums.net
When developing an application in C# you will often need to parse data from an external API to complete a certain task. As APIs get more complex writing out JSON classes is time consuming and you might not have time to write out a parser by hand due to strict deadlines. This tutorial discusses how you can quickly parse JSON data in C# and be a more productive programmer.

Step 1) Create a class library project and reference it in your application. (Optional)

This is an optional step that will keep your code base cleaner. If you haven’t already, open your project in Visual Studio, add a new project to your solution and use the class library template. Name it something like YourNameSpace.Application.Json or a name you feel comfortable with (there’s not a right or wrong answer here, it’s personal preference, try to make something other developers will understand though!).

Step 2) Get a copy of the JSON Data you’ll be parsing

Before anything else you’ll need to grab a copy of the JSON Data that you need to parse. I’ll be using the following data throughout my examples.

JSON:
// https://jsonplaceholder.typicode.com/todos/1
{
  "userId": 1,
  "id": 1,
  "title": "delectus aut autem",
  "completed": false
}
Step 3) Open Quicktype

Open the QuickType App (https://quicktype.io/). The language defaults to Swift, you’ll need to change it to C# (Quicktype supports several programming languages). Take the namespace you choose earlier and copy it into the generated namespace field. Choose a memorable name for your class. And then copy and paste the JSON data into the field. You’ll get output that looks something like the following code.

C#:
// <auto-generated />
//
// To parse this JSON data, add NuGet 'Newtonsoft.Json' then do:
//
//    using Nathaniel.App.Json;
//
//    var toDo = ToDo.FromJson(jsonString);

namespace Nathaniel.App.Json
{
    using System;
    using System.Collections.Generic;

    using System.Globalization;
    using Newtonsoft.Json;
    using Newtonsoft.Json.Converters;

    public partial class ToDo
    {
        [JsonProperty("userId")]
        public long UserId { get; set; }

        [JsonProperty("id")]
        public long Id { get; set; }

        [JsonProperty("title")]
        public string Title { get; set; }

        [JsonProperty("completed")]
        public bool Completed { get; set; }
    }

    public partial class ToDo
    {
        public static ToDo FromJson(string json) => JsonConvert.DeserializeObject<ToDo>(json, Nathaniel.App.Json.Converter.Settings);
    }

    public static class Serialize
    {
        public static string ToJson(this ToDo self) => JsonConvert.SerializeObject(self, Nathaniel.App.Json.Converter.Settings);
    }

    internal static class Converter
    {
        public static readonly JsonSerializerSettings Settings = new JsonSerializerSettings
        {
            MetadataPropertyHandling = MetadataPropertyHandling.Ignore,
            DateParseHandling = DateParseHandling.None,
            Converters =
            {
                new IsoDateTimeConverter { DateTimeStyles = DateTimeStyles.AssumeUniversal }
            },
        };
    }
}
Step 4) Use your class

Once your class has been created and saved into your application it’s easy to use and is simple as adding the following two lines to your application. using Nathaniel.App.Json; var toDo = ToDo.FromJson(jsonString);., Visual Studio will add any NuGet packages you need for the class you created to work properly and with that you’re ready to keep coding.

Conclusion

QuickType is an helpful to remain productive in time-stresses situations and is one of the easiest ways to parse JSON data in C#.