-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathEnumToJson.cs
134 lines (116 loc) · 3.84 KB
/
EnumToJson.cs
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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
using System;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Serialization;
// Original enum with the StringEnumConverter attribute
[JsonConverter(typeof(StringEnumConverter))]
public enum UserRole
{
Admin = 0,
User = 1,
Moderator = 2,
Guest = 3
}
// User class with the enum property
public class User
{
public int Id { get; set; }
public string Name { get; set; }
public UserRole Role { get; set; }
}
public class Program
{
public static void Main()
{
var user = new User
{
Id = 1,
Name = "John Doe",
Role = UserRole.Admin
};
// Method 1: Using JsonSerializerSettings with attribute overrides
var settings1 = new JsonSerializerSettings
{
ContractResolver = new IgnoreJsonConverterContractResolver()
};
string jsonWithOverride = JsonConvert.SerializeObject(user, settings1);
Console.WriteLine("Method 1 (ContractResolver): " + jsonWithOverride);
// Method 2: Using specific JsonConverter with NullValueHandling
var settings2 = new JsonSerializerSettings
{
Converters = new JsonConverter[] { new IntEnumConverter() }
};
string jsonWithIntConverter = JsonConvert.SerializeObject(user, settings2);
Console.WriteLine("Method 2 (Custom Converter): " + jsonWithIntConverter);
}
}
// Method 1: A custom ContractResolver that ignores JsonConverter attributes
public class IgnoreJsonConverterContractResolver : DefaultContractResolver
{
protected override JsonContract CreateContract(Type objectType)
{
JsonContract contract = base.CreateContract(objectType);
// Remove JsonConverter for enums (keeps other converters intact)
if (objectType.IsEnum)
{
contract.Converter = null;
}
return contract;
}
}
// Method 2: A custom JsonConverter for enums that forces integer serialization
public class IntEnumConverter : JsonConverter
{
public override bool CanConvert(Type objectType)
{
return objectType.IsEnum;
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
if (reader.TokenType == JsonToken.Number)
{
return Enum.ToObject(objectType, Convert.ToInt32(reader.Value));
}
else if (reader.TokenType == JsonToken.String)
{
// Handle string case if needed
if (Enum.TryParse(objectType, reader.Value.ToString(), out object result))
{
return result;
}
}
return existingValue ?? Enum.GetValues(objectType).GetValue(0);
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
// Write the enum as an integer
writer.WriteValue(Convert.ToInt32(value));
}
}
// Extension method approach
public static class JsonExtensions
{
public static string SerializeWithIntEnums<T>(this T obj)
{
var settings = new JsonSerializerSettings
{
ContractResolver = new IgnoreJsonConverterContractResolver()
};
return JsonConvert.SerializeObject(obj, settings);
}
}
// Usage of the extension method:
// string json = user.SerializeWithIntEnums();
// BONUS: Using JsonSerializerSettings when registering in ASP.NET Core
/*
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers()
.AddNewtonsoftJson(options =>
{
options.SerializerSettings.ContractResolver = new IgnoreJsonConverterContractResolver();
// Or alternatively:
// options.SerializerSettings.Converters.Add(new IntEnumConverter());
});
}
*/