JsonEnumDisplayConverter.cs 1.62 KB
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace NCC.Code.JsonSerialization
{
    public class JsonEnumDisplayConverter : JsonConverter
    {
        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            try
            {

                var t = value.GetType().GetFields().SingleOrDefault(w => w.Name == value.ToString()).CustomAttributes.SingleOrDefault(w => w.AttributeType == typeof(DescriptionAttribute));
                //var t = value.GetType().GetFields().SingleOrDefault(w => w.Name == value.ToString()).CustomAttributes.SingleOrDefault(w => w.AttributeType == typeof(DisplayAttribute));
                if (t != null)
                {
                    writer.WriteValue(t.ConstructorArguments[0].Value.ToString());
                }
                else
                {
                    writer.WriteValue(value.ToString());

                }
            }
            catch
            {

                writer.WriteValue("");
            }
        }

        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            throw new NotImplementedException("Unnecessary because CanRead is false. The type will skip the converter.");
        }

        public override bool CanRead => false;

        public override bool CanConvert(Type objectType)
        {
            return objectType == typeof(string);
        }
    }
}