using System.Collections; using System.Reflection; namespace XFEExtension.NetCore.XFEJsonTransform; /// /// XFEJson转换器 /// public static class XFEJsonTransformer { #region 对象转Json字符串 /// /// 将对象转换为Json字符串 /// /// /// /// 空对象异常 public static string? ConvertToJson(this object obj) { if (obj is null) { throw new XFEJsonTransformException("对象为空"); } Type type = obj.GetType(); if (IsSimpleType(type)) { return GetSimpleValueAsString(obj); } if (type.IsArray || typeof(IEnumerable).IsAssignableFrom(type)) { return ConvertArrayOrEnumerableToJson(obj); } return ConvertObjectToJson(obj); } private static bool IsSimpleType(Type type) { return type.IsPrimitive || type == typeof(string) || type == typeof(decimal) || type == typeof(DateTime); } private static string? GetSimpleValueAsString(object value) { if (value is string) { return $"\"{value}\""; } if (value is DateTime dateTime) { return $"\"{dateTime:s}\""; } if (value is bool boolValue) { return boolValue ? "true" : "false"; } return value.ToString(); } private static string ConvertArrayOrEnumerableToJson(object obj) { if (obj is IEnumerable array) { var jsonElements = new List(); foreach (var item in array) { var json = item.ConvertToJson(); if (json is not null) jsonElements.Add(json); else jsonElements.Add(string.Empty); } return $"[{string.Join(",", jsonElements)}]"; } return string.Empty; } private static string ConvertObjectToJson(object obj) { var type = obj.GetType(); var properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance) .Where(p => p.CanRead); var jsonProperties = new List(); foreach (var property in properties) { var propertyName = property.Name; var propertyValue = property.GetValue(obj); if (propertyValue is null) { jsonProperties.Add($"\"{propertyName}\":null"); } else { if (property.PropertyType.IsEnum) { jsonProperties.Add($"\"{propertyName}\":{(int)propertyValue}"); } else { jsonProperties.Add($"\"{propertyName}\":{propertyValue.ConvertToJson()}"); } } } return $"{{{string.Join(",", jsonProperties)}}}"; } #endregion #region Json字符串转对象 /// /// 将Json字符串转换为对象 /// /// 待转换的类型 /// /// /// public static T ConvertFromJson(string jsonString) where T : new() { if (string.IsNullOrEmpty(jsonString)) { throw new ArgumentException("Json字符串为空"); } var jsonObject = (T)Activator.CreateInstance(typeof(T))!; var jsonProperties = GetJsonProperties(jsonString); var objectType = typeof(T); foreach (var jsonProperty in jsonProperties) { var propertyName = jsonProperty.Key; var propertyValue = jsonProperty.Value; var property = objectType.GetProperty(propertyName); if (property is not null) { var convertedValue = ConvertToPropertyValue(propertyValue, property.PropertyType); property.SetValue(jsonObject, convertedValue); } } return jsonObject; } private static Dictionary GetJsonProperties(string jsonString) { var jsonProperties = new Dictionary(); var jsonTokens = jsonString.Trim('{', '}').Split(','); foreach (var jsonToken in jsonTokens) { var propertyParts = jsonToken.Split(':'); if (propertyParts.Length == 2) { var propertyName = propertyParts[0].Trim('\"'); var propertyValue = propertyParts[1].Trim(); jsonProperties[propertyName] = propertyValue; } } return jsonProperties; } private static object ConvertToPropertyValue(string propertyValue, Type targetType) { if (targetType == typeof(string)) { return propertyValue.Trim('\"'); } if (targetType == typeof(int)) { return int.Parse(propertyValue); } if (targetType == typeof(decimal)) { return decimal.Parse(propertyValue); } if (targetType == typeof(DateTime)) { return DateTime.Parse(propertyValue.Trim('\"')); } if (targetType.IsEnum) { return Enum.Parse(targetType, propertyValue); } throw new NotSupportedException($"不支持的属性类型: {targetType.Name}"); } #endregion }