using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Serialization;
using System;
using System.Collections.Generic;
using System.Linq;namespace Vip.System.Model
{public class JsonUtils{/// /// Json 序列化/// 1. 按首字母排序/// 2. 时间格式化去除 T/// 3. 所有参数转小写/// 4. 格式化 Decimal 数据类型 2位小数形式/// /// /// public static string serializeObject(object obj){JsonSerializerSettings setting = new JsonSerializerSettings{NullValueHandling = NullValueHandling.Ignore, ContractResolver = new LowerContractResolver(), //转换小写字母Converters = new List() {new Newtonsoft.Json.Converters.IsoDateTimeConverter(){ DateTimeFormat="yyyy-MM-dd HH:mm:ss" }}};//格式化 Decimal 数据类型 2位小数形式setting.Converters.Add(new DecimalFormatConverter());string strData = JsonConvert.SerializeObject(obj, Formatting.None, setting);JObject jobject = JObject.Parse(strData);SortedDictionary target = KeySort(jobject);string jsonStr = JsonConvert.SerializeObject(target);return jsonStr;}/// /// 排序/// /// /// public static SortedDictionary KeySort(JObject obj){var res = new SortedDictionary();foreach (var x in obj){if (x.Value is JValue) res.Add(x.Key, x.Value);else if (x.Value is JObject) res.Add(x.Key, KeySort((JObject)x.Value));else if (x.Value is JArray){var tmp = new SortedDictionary[x.Value.Count()];for (var i = 0; i < x.Value.Count(); i++){tmp[i] = KeySort((JObject)x.Value[i]);}res.Add(x.Key, tmp);}}return res;}}/// /// 转换小写/// public class LowerContractResolver: DefaultContractResolver{protected override string ResolvePropertyName(string propertyName){return propertyName.ToLower();}}/// /// 格式化Decimal/// public class DecimalFormatConverter : JsonConverter{public override bool CanConvert(Type objectType){return (objectType == typeof(decimal));}public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer){writer.WriteValue(string.Format("{0:N2}",value));}public override bool CanRead{get { return false; }}public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer){throw new NotImplementedException();}}
}
本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!