Json轉換(二)

CodeAgriculture發表於2013-04-26
       ///    
        /// 物件轉換為Json字串   
        ///
   
        /// 物件   
        /// Json字串   
        public static string ToJson(object jsonObject)
        {
            string jsonString = "{";
            PropertyInfo[] propertyInfo = jsonObject.GetType().GetProperties();
            for (int i = 0; i < propertyInfo.Length; i++)
            {
                string value = string.Empty;
                object bjectValue = propertyInfo[i].GetGetMethod().Invoke(jsonObject, null);
                //當VO中的屬性是其他VO即一對多並且是泛型
                if (propertyInfo[i].GetValue(jsonObject, null)!=null&&propertyInfo[i].GetValue(jsonObject, null).GetType().IsGenericType)
                {
                    object bj = propertyInfo[i].GetValue(jsonObject, null);
                    Type bjType = obj.GetType();
                    int count = Convert.ToInt32(objType.GetProperty("Count").GetValue(obj, null));
                    if (count > 0)
                    {
                        for (int k = 0; k < count; k++)
                        {
                            object listItem = objType.GetProperty("Item").GetValue(obj, new object[] { k });
                            if(k                                value += ToJson(listItem)+",";
                            else
                                value += ToJson(listItem);
                        }
                        jsonString += "\"" + propertyInfo[i].Name + "\":[" + value + "],";
                    }
                }
                else
                {
                    //當VO中的屬性是其他VO
                    Type type = propertyInfo[i].PropertyType;
                    if (type.FullName.Contains("PART.Models"))
                    {
                        PropertyInfo[] subpropertyInfo = objectValue.GetType().GetProperties();
                        if (subpropertyInfo.Length > 0)
                        {
                            value = ToJson(objectValue);
                            jsonString += "\"" + propertyInfo[i].Name + "\":" + value + ",";
                        }
                    }
                    else
                    {
                        value = bjectValue == null ? "" : objectValue.ToString();
                        jsonString += "\"" + propertyInfo[i].Name + "\":" + StringFormat(value, type) + ",";
                    }
                }
            }
            jsonString=jsonString.Remove(jsonString.Length - 1,1);
            return jsonString + "}";
        }

        ///  
        /// 格式化字元型、日期型、布林型  
        ///
 
        ///  
        ///  
        ///  
        private static string StringFormat(string str, Type type)
        {
            Type p_date=Type.GetType("string");
            if (type == typeof(string))
            {
                str = String2Json(str);
                str = "\"" + str + "\"";
            }
            else if (type == typeof(DateTime) ||IsNullableDate(type))
            {
                if (str!="")
                    str = "\"" + (Convert.ToDateTime(str)).ToString("yyyy/MM/dd") + "\"";
                else
                    str = "\"" + str + "\"";
            }
            else if (type == typeof(bool))
            {
                str = str.ToLower();
            }
            else if (type == typeof(IEnumerable))
            {
                str = "\"" + ((IEnumerable)str).ToString() + "\"";
            }
            else
            {
                str = "\"" + str + "\"";
            }
            return str;
        }

        private static bool IsNullableDate(Type type)
        {
            bool flag = false;

            if (type.ToString().Contains("System.Nullable"))
            {
                string m_type = type.ToString().Substring(type.ToString().IndexOf('[') + 1);
                m_type = m_type.Remove(m_type.LastIndexOf(']'));
                if(m_type.Equals("System.DateTime"))
                   flag = true;
            }
            return flag;
        }

        ///  
        /// 過濾特殊字元  
        ///
 
        ///  
        ///  
        public static string String2Json(String s)
        {
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < s.Length; i++)
            {
                char c = s.ToCharArray()[i];
                switch (c)
                {
                    case '\"':
                        sb.Append("\\\""); break;
                    case '\\':
                        sb.Append("\\\\"); break;
                    case '/':
                        sb.Append("\\/"); break;
                    case '\b':
                        sb.Append("\\b"); break;
                    case '\f':
                        sb.Append("\\f"); break;
                    case '\n':
                        sb.Append("\\n"); break;
                    case '\r':
                        sb.Append("\\r"); break;
                    case '\t':
                        sb.Append("\\t"); break;
                    default:
                        sb.Append(c); break;
                }
            }
            return sb.ToString();
        }
注:Json轉換(一二三)放在同一個Static類中

來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/28699126/viewspace-759362/,如需轉載,請註明出處,否則將追究法律責任。

相關文章