public static class ExensionJSON
{
public static string ToJSONList(Type t,List<Object> source)
{
string returnValue = "";
StringBuilder sb = new StringBuilder();
sb.Append("[");
foreach (var item in source)
{
sb.Append(ToJSON(t,item) + ",");
}
sb.Append("]");
returnValue = sb.ToString();
returnValue = Regex.Replace(returnValue, @",]", "]");
return returnValue;
}
public static string ToJSON(Type t,Object source)
{
string returnValue = "";
StringBuilder sb = new StringBuilder();
sb.Append("{");
PropertyInfo[] properties = t.GetProperties();
foreach (PropertyInfo property in properties)
{
object propertyValue = property.GetValue(source, null);
if (propertyValue!=null && !String.IsNullOrWhiteSpace(propertyValue.ToString()))
{
sb.Append(string.Format("\"{0}\":\"{1}\",", property.Name, propertyValue));
}
else {
sb.Append(string.Format("\"{0}\":null,", property.Name));
}
}
sb.Append("}");
returnValue = sb.ToString();
returnValue = Regex.Replace(returnValue, @",}", "}");
return returnValue;
}
}