Blame view

netcore/src/Infrastructure/NCC/JsonSerialization/Converters/JsonEnumDisplayConverter.cs 1.62 KB
de2bd2f9   “wangming”   项目初始化
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
  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);
          }
      }
  }