public static string ToJson<T>(IEnumerable<T> enumerable) where T : new() { var tor = enumerable.GetEnumerator(); if (!tor.MoveNext()) { return "[]"; } StringBuilder result = new StringBuilder("["); var entityType = typeof(T); do { bool first = true; foreach (var property in EntityUtility.GetEnumerable(entityType)) { if (!property.EntityProperty.CanRead) { continue; } if (first) { result.Append('{').Append(property.MappedName).Append(':'); AppendJSONValue(result, property.EntityProperty.PropertyType, property.GetValue(tor.Current)); first = false; } else { result.Append(',').Append(property.MappedName).Append(':'); AppendJSONValue(result, property.EntityProperty.PropertyType, property.GetValue(tor.Current)); } } result.Append("},"); } while (tor.MoveNext()); result.Length--; return result.Append(']').ToString(); } public static IEnumerable<T> ToEnumerable<T>(string json) where T : new() { string[] array = Regex.Split(json, ",{"); if (array.Length == 0) { yield break; } var entityType = typeof(T); Func<string, T> func = jObj => { T entity = Activator.CreateInstance<T>(); foreach (var property in EntityUtility.GetEnumerable(entityType)) { if (!property.EntityProperty.CanWrite) { continue; } foreach (string dictionarys in jObj.Split(',')) { string[] dictionary = dictionarys.Split(':'); if (dictionary.Length == 2 && dictionary[0] == property.MappedName) { switch (Type.GetTypeCode(property.EntityProperty.PropertyType)) { case TypeCode.Boolean: property.SetValue(entity, dictionary[1] == "true"); break; case TypeCode.DateTime: string[] time = dictionary[1].Substring(9, dictionary[1].Length - 10).Split(','); property.SetValue(entity, new DateTime(int.Parse(time[0]), int.Parse(time[1]) + 1, int.Parse(time[2]), int.Parse(time[3]), int.Parse(time[4]), int.Parse(time[5]))); break; case TypeCode.String: property.SetValue(entity, dictionary[1].Substring(1, dictionary[1].Length - 2)); break; default: property.SetValue(entity, property.ChangeType(dictionary[1])); break; } } } } return entity; }; yield return func(String.Concat("{", array[0])); for (int i = 1; i < array.Length; i++) { yield return func(array[i]); } } internal static void AppendJSONValue(StringBuilder buffer, Type type, object value) { if (value == null) { buffer.Append("null"); return; } switch (Type.GetTypeCode(type)) { case TypeCode.Boolean: buffer.Append(value.ToString().ToLower()); break; case TypeCode.DateTime: DateTime time = Convert.ToDateTime(value); buffer.Append("new Date(") .Append(time.Year).Append(',') .Append(time.Month - 1).Append(',') .Append(time.Day).Append(',') .Append(time.Hour).Append(',') .Append(time.Minute).Append(',') .Append(time.Second).Append(')'); break; case TypeCode.String: buffer.Append('"').Append(value.ToString() .Replace("\r\n", string.Empty) .Replace("\n", string.Empty) .Replace("\"", string.Empty)).Append('"'); break; default: buffer.Append(value); break; } }