JSONHelper.cs :  » Content-Management-Systems-CMS » Kooboo » Everest » Library » Json » C# / CSharp Open Source

Home
C# / CSharp Open Source
1.2.6.4 mono .net core
2.2.6.4 mono core
3.Aspect Oriented Frameworks
4.Bloggers
5.Build Systems
6.Business Application
7.Charting Reporting Tools
8.Chat Servers
9.Code Coverage Tools
10.Content Management Systems CMS
11.CRM ERP
12.Database
13.Development
14.Email
15.Forum
16.Game
17.GIS
18.GUI
19.IDEs
20.Installers Generators
21.Inversion of Control Dependency Injection
22.Issue Tracking
23.Logging Tools
24.Message
25.Mobile
26.Network Clients
27.Network Servers
28.Office
29.PDF
30.Persistence Frameworks
31.Portals
32.Profilers
33.Project Management
34.RSS RDF
35.Rule Engines
36.Script
37.Search Engines
38.Sound Audio
39.Source Control
40.SQL Clients
41.Template Engines
42.Testing
43.UML
44.Web Frameworks
45.Web Service
46.Web Testing
47.Wiki Engines
48.Windows Presentation Foundation
49.Workflows
50.XML Parsers
C# / C Sharp
C# / C Sharp by API
C# / CSharp Tutorial
C# / CSharp Open Source » Content Management Systems CMS » Kooboo 
Kooboo » Everest » Library » Json » JSONHelper.cs
/*
Kooboo is a content management system based on ASP.NET MVC framework. Copyright 2009 Yardi Technology Limited.

This program is free software: you can redistribute it and/or modify it under the terms of the
GNU General Public License version 3 as published by the Free Software Foundation.

This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU General Public License for more details.

You should have received a copy of the GNU General Public License along with this program.
If not, see http://www.kooboo.com/gpl3/.
*/
using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.Serialization;
using System.Web.Script.Serialization;
using System.Web.Configuration;
using System.Configuration;
using System.Web.Compilation;
using System.Collections;
using System.Linq;
using System.Text.RegularExpressions;

using Everest.Library.Extjs;
using System.Globalization;
namespace Everest.Library.Json{
    public static class JSONHelper
    {
        static readonly long DatetimeMinTimeTicks = new DateTime(0x7b2, 1, 1, 0, 0, 0, DateTimeKind.Utc).Ticks;

        static JavaScriptSerializer jsonSerializer = new JavaScriptSerializer();
        static JSONHelper()
        {
            ScriptingJsonSerializationSection settings = (ScriptingJsonSerializationSection)ConfigurationManager.GetSection("system.web.extensions/scripting/webServices/jsonSerialization");
            jsonSerializer.MaxJsonLength = settings.MaxJsonLength;
            jsonSerializer.RecursionLimit = settings.RecursionLimit;
            jsonSerializer.RegisterConverters(CreateConverters(settings.Converters));
        }
        internal static JavaScriptConverter[] CreateConverters(ConvertersCollection converters)
        {
            List<JavaScriptConverter> list = new List<JavaScriptConverter>();
            foreach (Converter converter in converters)
            {
                Type c = BuildManager.GetType(converter.Type, false);
                list.Add((JavaScriptConverter)Activator.CreateInstance(c));
            }
            return list.ToArray();
        }


        /// <summary>
        /// Toes the JSON.
        /// </summary>
        /// <param name="obj">The obj.</param>
        /// <returns></returns>
        public static string ToJSON(this object obj)
        {
            return jsonSerializer.Serialize(obj);
        }
        /// <summary>
        /// Deserilizes the JSON.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="json">The json.</param>
        /// <returns></returns>
        public static T DeserializeJSON<T>(this string json)
        {
            return jsonSerializer.Deserialize<T>(json);
        }

        /// <summary>
        /// Toes the ext store JSON.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="objs">The objs.</param>
        /// <returns></returns>
        public static string ToExtStoreJSON<T>(this IEnumerable<T> objs)
        {
            if (objs == null || objs.Count() == 0)
            {
                return "";
            }
            ExtJsonReaderObject jsonReader = new ExtJsonReaderObject(objs, objs.Count());
            return ToJSON(jsonReader);
        }

        /// <summary>
        /// Toes the ext store JSON.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="objs">The objs.</param>
        /// <param name="totalCount">The total count.</param>
        /// <returns></returns>
        public static string ToExtStoreJSON<T>(this IEnumerable objs, int totalCount)
        {
            ExtJsonReaderObject jsonReader = new ExtJsonReaderObject(objs, totalCount);
            return ToJSON(jsonReader);
        }

        /// <summary>
        /// Deserializes the string into date time.
        /// </summary>
        /// <param name="s">The s.</param>
        /// <returns></returns>
        public static DateTime DeserializeStringIntoDateTime(this string s)
        {
            long num;
            Match match = Regex.Match(s, "^/Date\\((?<ticks>-?[0-9]+)(?:[a-zA-Z]|(?:\\+|-)[0-9]{4})?\\)/");
            if (long.TryParse(match.Groups["ticks"].Value, out num))
            {
                return new DateTime((num * 0x2710L) + DatetimeMinTimeTicks, DateTimeKind.Utc);
            }
            return DateTime.MinValue;
        }


        /// <summary>
        /// Quotes the string.
        /// </summary>
        /// <param name="value">The value.</param>
        /// <returns></returns>
        public static string QuoteString(string value)
        {
            StringBuilder builder = null;
            if (string.IsNullOrEmpty(value))
            {
                return string.Empty;
            }
            int startIndex = 0;
            int count = 0;
            for (int i = 0; i < value.Length; i++)
            {
                char c = value[i];
                if ((((c == '\r') || (c == '\t')) || ((c == '"') || (c == '\''))) || ((((c == '<') || (c == '>')) || ((c == '\\') || (c == '\n'))) || (((c == '\b') || (c == '\f')) || (c < ' '))))
                {
                    if (builder == null)
                    {
                        builder = new StringBuilder(value.Length + 5);
                    }
                    if (count > 0)
                    {
                        builder.Append(value, startIndex, count);
                    }
                    startIndex = i + 1;
                    count = 0;
                }
                switch (c)
                {
                    case '<':
                    case '>':
                    case '\'':
                        {
                            AppendCharAsUnicode(builder, c);
                            continue;
                        }
                    case '\\':
                        {
                            builder.Append(@"\\");
                            continue;
                        }
                    case '\b':
                        {
                            builder.Append(@"\b");
                            continue;
                        }
                    case '\t':
                        {
                            builder.Append(@"\t");
                            continue;
                        }
                    case '\n':
                        {
                            builder.Append(@"\n");
                            continue;
                        }
                    case '\f':
                        {
                            builder.Append(@"\f");
                            continue;
                        }
                    case '\r':
                        {
                            builder.Append(@"\r");
                            continue;
                        }
                    case '"':
                        {
                            builder.Append("\\\"");
                            continue;
                        }
                }
                if (c < ' ')
                {
                    AppendCharAsUnicode(builder, c);
                }
                else
                {
                    count++;
                }
            }
            if (builder == null)
            {
                return value;
            }
            if (count > 0)
            {
                builder.Append(value, startIndex, count);
            }
            return builder.ToString();
        }

        /// <summary>
        /// Appends the char as unicode.
        /// </summary>
        /// <param name="builder">The builder.</param>
        /// <param name="c">The c.</param>
        private static void AppendCharAsUnicode(StringBuilder builder, char c)
        {
            builder.Append(@"\u");
            builder.AppendFormat(CultureInfo.InvariantCulture, "{0:x4}", new object[] { (int)c });
        }


        /// <summary>
        /// Quotes the string.
        /// </summary>
        /// <param name="value">The value.</param>
        /// <param name="addQuotes">if set to <c>true</c> [add quotes].</param>
        /// <returns></returns>
        public static string QuoteString(string value, bool addQuotes)
        {
            string str = QuoteString(value);
            if (addQuotes)
            {
                str = "\"" + str + "\"";
            }
            return str;
        }

 

 

    }
}

www.java2v.com | Contact Us
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.