Tuesday Coding Tip 26 — JSON (de)serialization in C#

●5 ●16 ●83
calendar_today • schedule2 min read
— Originally published at medium.com

Tuesday coding tips are super short posts about various tidbits mainly from C++, but also from other programming languages I use. You can also follow the #TuesdayCodingTips hashtag on Mastodon and Linkedin.


In need of a JSON (de)serializer in C#? One option could be to use the built-in System.Text.Json functionality. Probably the most popular way is to use the Newtonsoft.Json library which has a richer feature set while maintaining overall simplicity.

Things are as simple as having a class with a bunch of public attributes and calling serialize on it. Those attributes don’t even have to be trivial types — anything from DateTime to HashSet can be easily handled.

Deserialization is similarly easy — if a key is present, it will be deserialized. If not, the default value for the attribute will be picked instead.

using Newtonsoft.Json;

namespace NetSandbox;

public class ExtendedValues
{
    public long ErrorCode { get; set; }

    public string Message { get; set; } = string.Empty;
};

public class Property
{
    public string Value { get; set; } = "";
};

public class Protocol
{
    public long Version { get; set; } = -1;

    [JsonProperty("extended", NullValueHandling = NullValueHandling.Ignore)]
    public ExtendedValues? ExtendedValues { get; set; } = default;


    [JsonProperty("machineGuid")]
    public Guid MachineGuid { get; set; }

    public List<Property> Properties { get; set; } = new List<Property>();
};

public static class Program
{
    public static void Main()
    {
        Protocol schema = new()
        {
            Version = 1,
            MachineGuid = Guid.NewGuid(),
            Properties = new List<Property> {
                new Property {
                    Value = "hello"
                },
                new Property {
                    Value = "world"
                }
            }
        };

        var json = JsonConvert.SerializeObject(schema);
        // {"Version":1,"machineGuid":"156717fd-0904-47af-bcb8-ad74d23b9cc7","Properties":[{"Value":"hello"},{"Value":"world"}]}

        var obj = JsonConvert.DeserializeObject<Protocol>(
            """{"machineGuid": "156717fd-0904-47af-bcb8-ad74d23b9cc7"}""");
        // obj.Version contains -1
        // obj.MachineGuid containts "156717fd-0904-47af-bcb8-ad74d23b9cc7"
        // obj.ExtendedValues is null
        // obj.Properties is empty list
    }
}

If you need to, you can use annotations to for example customize the name of the serialized property or whether it will be serialized when it is null.

Extra thought: I originally wrote this post in late 2023. Since then, many people would probably advice you System.Text.Json on the merit of being faster and getting more and more on-part with Newtonsoft on each major release. Since we did a switch to it some time ago, I cannot wholeheartedly recommend it - it is great for simple use cases, but once you have some data structure that evolved over time and you need to be lenient of what you accept over wire and strict in what you send, working with System.Text.Json is a bigger pain, especially around NullValueHandling and DefaultValueHandling.

Part 26 of 28 in Tuesday Coding Tips

2 Comments

0 votes
1
🔥 Join developers growing publicly
Share your knowledge, build in public, and grow your developer presence with a global community.

More Posts

Tuesday Coding Tip 06 - Explicit template instantiation

Jakub Neruda - Apr 7

Tuesday Coding Tip 02 - Template with type-specific API

Jakub Neruda - Mar 10

Tuesday Coding Tip 28 — (de)serializing JSON string enum in C#

Jakub Neruda - Oct 27

Tuesday Coding Tip 27 — Aliasing and ‘using’ in C++

Jakub Neruda - Oct 20

Tuesday Coding Tip 05 - Object initialization in C++

Jakub Neruda - Mar 31
chevron_left
1.9k Points • 104 Badges
Brno, Czech Republic • linkedin.com/in/jakub-neruda
35Posts
35Comments
21Connections
Experienced C++ developer, team lead and hobby gamedev. I enjoy writing stuff about C++, clean code, clean architecture, and game development.

Related Jobs

View all jobs →

Commenters (This Week)

8 comments
1 comment
1 comment

Contribute meaningful comments to climb the leaderboard and earn badges!