Click here to Skip to main content
15,891,777 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 81.4K   2K   79  
A small LinqToJSON library in C#, and how it works
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Ranslant.JSON.Linq
{
    public class JArray : IJValue
    {
        // a LinkedList<IJvalue> would be more efficient memory-wise, but only for big amounts of values
        // an array might be better memory-wise, but is not so comfortable to use since I do not know in
        // advance how many elements I will have. And then why reinvent the wheel?
        private List<IJValue> _elements;

        private int _capacity = 15;     // 15 elements at a time should be enough to stay memory efficient ...
                                        // this is a bit arbitrary, but I am still looking for a better alternative
        public JArray()
        {
        }

        /// <summary>
        /// Allows to set the initial capacity of the private value container
        /// </summary>
        /// <param name="capacity">int specifying the initial capacity</param>
        public JArray(int capacity)
        {
            _capacity = capacity;
        }

        /// <summary>
        /// Creates a JSON array pre-filled with the jValues
        /// </summary>
        /// <param name="jValues">JSON values, as instances of the classes implementing IJValues (JString, JNumber, JObject, etc.)</param>
        public JArray(params IJValue[] jValues)
        {
            this.Add(jValues);
        }
        
        #region IJValue Members

        public new string ToString()
        {
            return this.ToString(0);
        }

        public string ToString(int indentLevel)
        {
            StringBuilder sb = new StringBuilder();
            int count = _elements.Count;

            string indent = indentLevel > 0 ? Utilities.MakeIndent(indentLevel) : string.Empty;

            sb.AppendLine(JToken.ArrayStart);

            foreach (IJValue element in _elements)
            {
                
                sb.Append(Utilities.MakeJSONTextLine(indent,
                    // do not add the separator for the last element
                    --count > 0,
                    element.ToString(indentLevel + 1)));
            }

            // one indent level back for the end delimiter
            if (indentLevel > 0)
            {
                indent = indent.Remove(0, 1);
                sb.Append(indent);
            }

            sb.Append(JToken.ArrayEnd);
            return sb.ToString();
        }
        #endregion

        /// <summary>
        /// Returns the amount of elements in the array
        /// </summary>
        public int Count
        {
            get { return _elements.Count; }
        }
        
        /// <summary>
        /// Returns the value stored at a specific index in the JArray
        /// </summary>
        /// <param name="index">index in the array of the value to return</param>
        /// <returns></returns>
        public IJValue this[int index]
        {
            get
            {
                return _elements.ElementAt(index);  // maybe we should rather use TryGetValue and raise an exception if needed?
            }
        }

        /// <summary>
        /// Adds JSON values to the JSON array
        /// </summary>
        /// <param name="jValues"></param>
        public void Add(params IJValue[] jValues)
        {
            if (_elements == null)
            {
                _elements = new List<IJValue>(jValues.Length > _capacity ? jValues.Length : _capacity);
            }

            foreach(IJValue jValue in jValues)
                _elements.Add(jValue);
        }

        /// <summary>
        /// Returns a list of all elements stored in the JSON array
        /// </summary>
        /// <returns>a list (as IEnumerable) of IJvalue items</returns>
        public IEnumerable<IJValue> GetValues()
        {
            return _elements;
        }
    }
}

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