JSON.net Mastering enums

Evgeny Zborovsky · March 21, 2017


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 { get; set; }  
    enum Unit  
        \[EnumMember(Value = "kgs")\]  
        \[EnumMember(Value = "lbs")\]  

Twitter, Facebook