示例#1
0
        /// <summary>
        /// Convert an object to a JSON string with the specified formatting
        /// </summary>
        /// <param name="obj">The obj.</param>
        /// <param name="propertyNamesCaseType">Type of the property names case.</param>
        /// <returns></returns>
        public static string ToJsonString(this object obj, PropertyNamesCaseType propertyNamesCaseType)
        {
            var type          = obj.GetType();
            var dateTimeStyle = "yyyy-MM-dd HH:mm:ss";

            if (type.IsPrimitive || typeof(string).IsAssignableFrom(type))
            {
                return(obj.ToString());
            }

            if (typeof(DateTime).IsAssignableFrom(type) || typeof(DateTimeOffset).IsAssignableFrom(type))
            {
                return(Convert.ToDateTime(obj).ToString(dateTimeStyle));
            }

            var serializer = new JsonSerializer();

            switch (propertyNamesCaseType)
            {
            case PropertyNamesCaseType.CamelCase:
                serializer.ContractResolver = new CamelCasePropertyNamesContractResolver();
                break;
            }

            var dateTimeConverter = new IsoDateTimeConverter
            {
                DateTimeStyles = System.Globalization.DateTimeStyles.None,
                DateTimeFormat = dateTimeStyle
            };

            if (typeof(IDictionary).IsAssignableFrom(type))
            {
                return(JObject.FromObject(obj, serializer).ToString(Formatting.None, dateTimeConverter));
            }

            if (type.IsArray || (typeof(IEnumerable).IsAssignableFrom(type)))
            {
                return(JArray.FromObject(obj, serializer).ToString(Formatting.None, dateTimeConverter));
            }

            return(JObject.FromObject(obj, serializer).ToString(Formatting.None, dateTimeConverter));
        }
 /// <summary>
 /// Convert an object to a JSON string with the specified formatting
 /// </summary>
 /// <param name="html"></param>
 /// <param name="obj"></param>
 /// <returns></returns>
 public static IHtmlString ToJsonString(this HtmlHelper html, object obj, PropertyNamesCaseType propertyNamesCaseType)
 {
     return(new HtmlString(obj.ToJsonString(propertyNamesCaseType)));
 }