JSON.net Mastering enums


Legacy backend API endpoint returns JSON with units in an uncommon manner.
Instead of returning the measurement system “imperial” or “metric” it returns “kgs” or “lbs”.


Using JSON.net deserialize & serialize “kgs” to “metric” and “lbs” to “imperial” in our front-end app.


The solution is pretty simple. We have to define an enum, with “EnumMember” attributes on each element and use “StringEnumConverter” as preferred JsonConvertor. Here is the full and working example:

using System;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;

namespace JSONnetEnums
    class Program
        static void Main(string[] args)
            var deserializedObj = 
            // Output: Metric

            var serializedObj = 
                JsonConvert.SerializeObject(new Foo { Unit = Unit.Imperial });
            // Output: {“Unit”:”lbs”}

    class Foo
        public Unit Unit { getset; }

    enum Unit
        [EnumMember(Value = kgs)]
        [EnumMember(Value = lbs)]

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 )

Twitter picture

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

Facebook photo

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

Connecting to %s