xuruiqian
2021-05-25 c0bbcd97fa2f130a7a60d02873fbf9038bdd4c15
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
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System;
using System.Data;
 
namespace GTech.Solution.Api.Common
{
    #region 一.忽略某些属性
    /// 一.忽略某些属性
    /// OptIn 默认情况下, 所有的成员不会被序列化, 类中的成员只有标有特性JsonProperty的才会被序列化, 当类的成员很多, 但客户端仅仅需要一部分数据时, 很有用
    /// [JsonObject(MemberSerialization.OptIn)]
    /// public class Person
    /// {
    ///     public int Age { get; set; }
    ///     [JsonProperty]
    ///     public string Name { get; set; }
    /// }
    /// Person p = new Person { Age = 10, Name = "Gary"};
    /// result: {"Name":"Gary"}
    /// 
    /// OptOut 默认值, 类中所有公有成员会被序列化, 如果不想被序列化, 可以用特性JsonIgnore
    /// [JsonObject(MemberSerialization.OptOut)]
    /// public class Person
    /// {
    ///     public int Age { get; set; }
    ///     [JsonIgnore]
    ///     public string Name { get; set; }
    /// }
    /// Person p = new Person { Age = 10, Name = "Gary"};
    /// result: {"Age":"10"}
    #endregion
 
    #region 二.默认值处理
    /// 二.默认值处理
    ///  序列化时想忽略默认值属性可以通过JsonSerializerSettings.DefaultValueHandling来确定,该值为枚举值
    /// DefaultValueHandling.Ignore 序列化和反序列化时, 忽略默认值
    /// DefaultValueHandling.Include 序列化和反序列化时, 包含默认值
    /// [JsonObject(MemberSerialization.OptIn)]
    /// public class Person
    /// {
    ///     [DefaultValue(10)]
    ///     public int Age { get; set; }
    ///     [JsonProperty]
    ///     public string Name { get; set; }
    /// }
    /// Person p = new Person { Age = 10, Name = "Gary", Sex = "Man", IsMarry = false, Birthday = new DateTime(1991, 1, 2) };
    /// result: {"Name":"Gary","Sex":"Man","Birthday":"1991-01-02T00:00:00"}
    #endregion
 
    #region 三.空值的处理
    /// 三.空值的处理
    ///  序列化时需要忽略值为NULL的属性,可以通过JsonSerializerSettings.NullValueHandling来确定,
    ///  另外通过JsonSerializerSettings设置属性是对序列化过程中所有属性生效的,
    ///  想单独对某一个属性生效可以使用JsonProperty,下面将分别展示两个方式
    /// [JsonObject(MemberSerialization.OptIn)]
    /// public class Person
    /// {
    ///     [JsonProperty(NullValueHandling=NullValueHandling.Ignore)] //Must set this attibute, otherwise throw exception.
    ///     public Room room { get; set; }
    ///     [JsonProperty]
    ///     public int Age { get; set; }
    ///     [JsonProperty]
    ///     public string Name { get; set; }
    /// }
    /// Person p = new Person { room = NULL,Age = 10, Name = "Gary"};
    /// result: {"Age":"10","Name":"Gary"}
 
    #endregion
 
    #region 四.支持非公共成员
    /// 四.支持非公共成员
    ///  序列化时默认都是处理公共成员,如果需要处理非公共成员,就要在该成员上加特性"JsonProperty"
    /// [JsonObject(MemberSerialization.OptIn)]
    /// public class Person
    /// {
    ///     [JsonProperty]
    ///     public int Age { get; set; }
    ///     [JsonProperty]
    ///     public string Name { get; set; }
    ///     [JsonProperty]
    ///     private int Height { get; set; }
    /// }
    /// Person p = new Person {Age = 10, Name = "Gary",Height = "100.1"};
    /// result: {"Age":"10","Name":"Gary","Height":"100.1"}
    #endregion
 
    #region 五.日期处理
    /// 五.日期处理
    ///  对于Dateime类型日期的格式化就比较麻烦了,系统自带的会格式化成iso日期标准,
    ///  但是实际使用过程中大多数使用的可能是yyyy-MM-dd 或者yyyy-MM-dd HH:mm:ss两种格式的日期,
    ///  解决办法是可以将DateTime类型改成string类型自己格式化好,然后在序列化。
    ///  如果不想修改代码,可以采用下面方案实现。
    ///  Json.Net提供了IsoDateTimeConverter日期转换这个类,可以通过JsnConverter实现相应的日期转换
    ///     [JsonConverter(typeof(IsoDateTimeConverter))]
    ///     public DateTime Birthday { get; set; }
    ///  但是IsoDateTimeConverter日期格式不是我们想要的,我们可以继承该类实现自己的日期
    /// public class ChinaDateTimeConverter : DateTimeConverterBase
    /// {
    ///     private static IsoDateTimeConverter dtConverter = new IsoDateTimeConverter { DateTimeFormat = "yyyy-MM-dd" };
    ///     public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    ///     {
    ///         return dtConverter.ReadJson(reader, objectType, existingValue, serializer);
    ///     }
    ///     public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    ///     {
    ///         dtConverter.WriteJson(writer, value, serializer);
    ///     }
    /// }
    ///     [JsonConverter(typeof(ChinaDateTimeConverter))]
    ///     public DateTime Birthday { get; set; }
    ///     
    /// [JsonObject(MemberSerialization.OptIn)]
    /// public class Person
    /// {
    ///     [JsonProperty]
    ///     public int Age { get; set; }
    ///     [JsonProperty]
    ///     public string Name { get; set; }
    ///     [JsonProperty]
    ///     private int Height { get; set; }
    ///     [JsonConverter(typeof(ChinaDateTimeConverter))]
    ///     public DateTime Birthday { get; set; }
    /// }
    /// Person p = new Person {Age = 10, Name = "Gary",Height = "100.1", Birthday = Birthday = new DateTime(1991, 1, 2)};
    /// result: {"Age":"10","Name":"Gary","Height":"100.1","Birthday":"1991-01-02-00-00-00"}
    #endregion
    public class JsonNetExt
    {
        #region Serialization
        public static string DataTableToJson(DataTable dt)
        {
            return JsonConvert.SerializeObject(dt);
        }
        public static string EntityToJson<T>(T Entity)
        {
            return JsonConvert.SerializeObject(Entity);
        }
        public static string EntityToJsonIgnoreDefaultValue<T>(T Entity)
        {
            JsonSerializerSettings jsetting = new JsonSerializerSettings();
            jsetting.DefaultValueHandling = DefaultValueHandling.Ignore;
 
            return JsonConvert.SerializeObject(Entity, Formatting.Indented, jsetting);
        }
        public static string EntityToJsonIgnoreNULL<T>(T Entity)
        {
            JsonSerializerSettings jsetting = new JsonSerializerSettings();
            jsetting.NullValueHandling = NullValueHandling.Ignore;
            return JsonConvert.SerializeObject(Entity, Formatting.Indented, jsetting);
        }
        public static string EntityToJsonIgnoreNULLAndDefaultValue<T>(T Entity)
        {
            JsonSerializerSettings jsetting = new JsonSerializerSettings();
            jsetting.NullValueHandling = NullValueHandling.Ignore;
            jsetting.DefaultValueHandling = DefaultValueHandling.Ignore;
            return JsonConvert.SerializeObject(Entity, Formatting.Indented, jsetting);
        }
        #endregion
 
        #region Deserialization
        public static DataTable JsonToDataTable(string dataTableJsonString)
        {
            return JsonConvert.DeserializeObject<DataTable>(dataTableJsonString);
        }
        public static T JsonToEntity<T>(string entityJsonString)
        {
            return JsonConvert.DeserializeObject<T>(entityJsonString);
        }
        #endregion
    }
    /// <summary>
    /// User defined time converter for convert to json string
    /// </summary>
    public class ChinaDateTimeConverter : DateTimeConverterBase
    {
        private static IsoDateTimeConverter dtConverter = new IsoDateTimeConverter { DateTimeFormat = "yyyy-MM-dd-hh-mm-ss" };
 
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            return dtConverter.ReadJson(reader, objectType, existingValue, serializer);
        }
 
        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            dtConverter.WriteJson(writer, value, serializer);
        }
    }
    /// <summary>
    /// MemberSerialization.OptOut: OptOut 默认值, 类中所有公有成员会被序列化, 如果不想被序列化, 可以用特性JsonIgnore
    /// MemberSerialization.OptOut: OptIn 默认情况下, 所有的成员不会被序列化, 类中的成员只有标有特性JsonProperty的才会被序列化, 当类的成员很多, 但客户端仅仅需要一部分数据时, 很有用
    /// </summary>
    [JsonObject(MemberSerialization.OptIn)]
    public class JsonNetExtDemoPerson
    {
        /// <summary>
        /// JsonProperty(NullValueHandling = NullValueHandling.Ignore): ignore null value properties
        /// </summary>
        [JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
        public object Data { get; set; }
        /// <summary>
        /// JsonIgnore: When converting ,Ignore this property
        /// </summary>
        [JsonIgnore]
        public int Age { get; set; }
        /// <summary>
        /// JsonProperty: When converting via MemberSerialization.OptIn, if include this property, must use this attribute.
        /// </summary>
        [JsonProperty]
        public string Name { get; set; }
        /// <summary>
        /// JsonProperty: if need private properties, must add this attribute
        /// </summary>
        [JsonProperty]
        private int Height { get; set; }
        /// <summary>
        /// ChinaDateTimeConverter: Use time converter, set time format by user.
        /// </summary>
        [JsonConverter(typeof(ChinaDateTimeConverter))]
        public DateTime Birthday { get; set; }
        /// <summary>
        /// StringEnumConverter: make "Type":"1" to "Type":"Mail"
        /// </summary>
        [JsonConverter(typeof(StringEnumConverter))]
        public JsonNetExtDemoNotifyType Type { get; set; }
    }
    public enum JsonNetExtDemoNotifyType
    {
        Mail = 0,
        SMS = 1
    }
}