ExensionJSON

View Code
 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;
        }
    }

 

posted on 2013-05-11 17:39  sajiao  阅读(182)  评论(0编辑  收藏  举报

导航

街边网