Click here to Skip to main content
15,881,812 members
Articles / Programming Languages / C#

Small LINQ to JSON Library

Rate me:
Please Sign up or sign in to vote.
4.96/5 (28 votes)
6 Dec 2011CPOL13 min read 80.8K   2K   79  
A small LinqToJSON library in C#, and how it works
using System.Text.RegularExpressions;
using System;

namespace Ranslant.JSON.Linq
{
    public class JString:IJValue
    {
        private const string AllowedEscapeCharacters = "\"\\/bfnrtu";
        private const string EscapedUFourDigits = "[0-9a-fA-F]{4}";
        /*
         this regular expression needs to be checked:
         1. does it accurately describe a JSON string (without start and end delimiters)
         2. does it make sense to use it?
         */
        //private const string Pattern = @"^([^\\""]|\\([\\""/bfnrt]|(u[0-9a-fA-F]{4})))*$";

        private const string InvalidString = "invalid string: ";
        
        private string _content;
        public string Content
        {
            get
            {
                return this._content;
            }
        }

        /// <summary>
        /// Content is checked for validity. An excpetion is thrown if an error is found.
        /// </summary>
        /// <param name="content"> the string that is contained withing the JString value; this string is validated</param>
        public JString(string content)
        {
            if(CheckEscapedCharacters(content))
                _content = content;
        }

        /// <summary>
        /// throws JsonExceptions if something is wrong with the strings
        /// </summary>
        /// <param name="content"></param>
        private bool CheckEscapedCharacters(string content)
        {
            bool nexCharIsEscaped = false;

            for (int i = 0; i < content.Length; i++ )
            {
                char charToTest = content[i];

                if (nexCharIsEscaped)
                {
                    // TODO use a regexp for the whole string?

                    if (JString.AllowedEscapeCharacters.IndexOf(charToTest) < 0)
                        throw new JsonException("character (" + charToTest + ") cannot be escaped");

                    if (charToTest == 'u')
                    {
                        // after a \u, we expect 4 hexa digits ( http://www.json.org/ )
                        if (i + 1 + 4 > content.Length)
                            throw new JsonException(InvalidString + content);

                        if (!Regex.IsMatch(content.Substring(i + 1, 4), EscapedUFourDigits))
                            throw new JsonException(InvalidString + content);
                    }

                    nexCharIsEscaped = false;
                }
                else
                {
                    if (charToTest == '\\')
                        nexCharIsEscaped = true;
                    if (charToTest == '"' && i < content.Length - 1)
                        throw new JsonException(InvalidString + content);
                }

             }
            return true;
        }

        #region IJValue Members

        public string ToString(int indentLevel)
        {
            return this.ToString();
        }

        public new string ToString()
        {
            return JToken.StringDelimiter + _content + JToken.StringDelimiter;
        }

        #endregion
    }
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer IPG
Germany Germany
since 2010: C# with WPF
since 2002: C++ (MFC / QT)
since 1995: C, Java, Pascal


"if a drummer can do it, anobody can" - Bruce Dickinson

Comments and Discussions