Example #1
0
        public override string ToString()
        {
            // Purpose: Convert a JObject into a string
            // Author : Scott Bakker
            // Created: 09/13/2019
            // LastMod: 08/11/2020
            StringBuilder result = new StringBuilder();

            result.Append('{');
            bool addComma = false;

            foreach (KeyValuePair <string, object> kv in _data)
            {
                if (addComma)
                {
                    result.Append(',');
                }
                else
                {
                    addComma = true;
                }
                result.Append(JsonRoutines.ValueToString(kv.Key));
                result.Append(':');
                result.Append(JsonRoutines.ValueToString(kv.Value));
            }
            result.Append('}');
            return(result.ToString());
        }
Example #2
0
        public string ToStringSorted()
        {
            // Purpose: Sort the keys before returning as a string
            // Author : Scott Bakker
            // Created: 10/17/2019
            // LastMod: 08/11/2020
            StringBuilder result = new StringBuilder();

            result.Append('{');
            bool       addComma = false;
            SortedList sorted   = new SortedList(_data);

            for (int i = 0; i < sorted.Count; i++)
            {
                if (addComma)
                {
                    result.Append(',');
                }
                else
                {
                    addComma = true;
                }
                result.Append(JsonRoutines.ValueToString(sorted.GetKey(i)));
                result.Append(':');
                result.Append(JsonRoutines.ValueToString(sorted.GetByIndex(i)));
            }
            result.Append('}');
            return(result.ToString());
        }
Example #3
0
        public override string ToString()
        {
            // Purpose: Convert this JArray into a string with no formatting
            // Author : Scott Bakker
            // Created: 09/13/2019
            // LastMod: 08/11/2020
            // Notes  : This could be implemented as ToStringFormatted(-1) but
            //          it is separate to get better performance.
            StringBuilder result = new StringBuilder();

            result.Append('[');
            bool addComma = false;

            foreach (object obj in _data)
            {
                if (addComma)
                {
                    result.Append(',');
                }
                else
                {
                    addComma = true;
                }
                result.Append(JsonRoutines.ValueToString(obj));
            }
            result.Append(']');
            return(result.ToString());
        }
Example #4
0
        internal string ToStringFormatted(ref int indentLevel)
        {
            // Purpose: Convert this JObject into a string with formatting
            // Author : Scott Bakker
            // Created: 10/17/2019
            // LastMod: 08/11/2020
            if (_data.Count == 0)
            {
                return("{}"); // avoid indent errors
            }
            StringBuilder result = new StringBuilder();

            result.Append('{');
            if (indentLevel >= 0)
            {
                result.AppendLine();
                indentLevel++;
            }
            bool addComma = false;

            foreach (KeyValuePair <string, object> kv in _data)
            {
                if (addComma)
                {
                    result.Append(',');
                    if (indentLevel >= 0)
                    {
                        result.AppendLine();
                    }
                }
                else
                {
                    addComma = true;
                }
                if (indentLevel > 0)
                {
                    result.Append(JsonRoutines.IndentSpace(indentLevel));
                }
                result.Append(JsonRoutines.ValueToString(kv.Key));
                result.Append(':');
                if (indentLevel >= 0)
                {
                    result.Append(' ');
                }
                result.Append(JsonRoutines.ValueToString(kv.Value, ref indentLevel));
            }
            if (indentLevel >= 0)
            {
                result.AppendLine();
                if (indentLevel > 0)
                {
                    indentLevel--;
                }
                result.Append(JsonRoutines.IndentSpace(indentLevel));
            }
            result.Append('}');
            return(result.ToString());
        }
Example #5
0
 public bool Contains(string key)
 {
     // Purpose: Identifies whether a key exists in the current JObject
     // Author : Scott Bakker
     // Created: 09/13/2019
     if (JsonRoutines.IsWhitespaceString(key))
     {
         throw new ArgumentNullException(nameof(key), JsonKeyError);
     }
     return(_data.ContainsKey(key));
 }
Example #6
0
        internal static JArray Parse(CharReader reader)
        {
            // Purpose: Convert a partial string into a JArray
            // Author : Scott Bakker
            // Created: 09/13/2019
            // LastMod: 08/11/2020
            if (reader == null || reader.Peek() == -1)
            {
                return(null);
            }
            JArray result = new JArray();

            JsonRoutines.SkipBOM(reader);
            JsonRoutines.SkipWhitespace(reader);
            if (reader.Peek() != '[')
            {
                throw new SystemException(
                          $"JSON Error: Unexpected token to start JArray: {reader.Peek()}");
            }
            reader.Read();
            do
            {
                JsonRoutines.SkipWhitespace(reader);
                // check for symbols
                if (reader.Peek() == ']')
                {
                    reader.Read();
                    break; // done building JArray
                }
                if (reader.Peek() == ',')
                {
                    // this logic ignores extra commas, but is ok
                    reader.Read();
                    continue;             // next value
                }
                if (reader.Peek() == '{') // JObject
                {
                    JObject jo = JObject.Parse(reader);
                    result.Add(jo);
                    continue;
                }
                if (reader.Peek() == '[') // JArray
                {
                    JArray ja = JArray.Parse(reader);
                    result.Add(ja);
                    continue;
                }
                // Get value as a string, convert to object
                string tempValue = JsonRoutines.GetToken(reader);
                result.Add(JsonRoutines.JsonValueToObject(tempValue));
            } while (true);
            return(result);
        }
Example #7
0
        internal string ToStringFormatted(ref int indentLevel)
        {
            // Purpose: Convert this JArray into a string with formatting
            // Author : Scott Bakker
            // Created: 10/17/2019
            // LastMod: 03/09/2021
            if (_data.Count == 0)
            {
                return("[]"); // avoid indent errors
            }
            StringBuilder result = new();

            result.Append('[');
            if (indentLevel >= 0)
            {
                result.AppendLine();
                indentLevel++;
            }
            bool addComma = false;

            foreach (object obj in _data)
            {
                if (addComma)
                {
                    result.Append(',');
                    if (indentLevel >= 0)
                    {
                        result.AppendLine();
                    }
                }
                else
                {
                    addComma = true;
                }
                if (indentLevel > 0)
                {
                    result.Append(JsonRoutines.IndentSpace(indentLevel));
                }
                result.Append(JsonRoutines.ValueToString(obj, ref indentLevel));
            }
            if (indentLevel >= 0)
            {
                result.AppendLine();
                if (indentLevel > 0)
                {
                    indentLevel--;
                }
                result.Append(JsonRoutines.IndentSpace(indentLevel));
            }
            result.Append(']');
            return(result.ToString());
        }
Example #8
0
 public void Remove(string key)
 {
     // Purpose: Remove an item from a JObject
     // Author : Scott Bakker
     // Created: 09/13/2019
     if (JsonRoutines.IsWhitespaceString(key))
     {
         throw new ArgumentNullException(nameof(key), JsonKeyError);
     }
     if (_data.ContainsKey(key))
     {
         _data.Remove(key);
     }
 }
Example #9
0
 public void Merge(JObject jo)
 {
     // Purpose: Merge a new JObject onto the current one
     // Author : Scott Bakker
     // Created: 09/17/2019
     // LastMod: 08/11/2020
     // Notes  : If any keys are duplicated, the new value overwrites the current value
     if (jo == null || jo.Count() == 0)
     {
         return;
     }
     foreach (string key in jo)
     {
         if (JsonRoutines.IsWhitespaceString(key))
         {
             throw new ArgumentNullException(nameof(key), JsonKeyError);
         }
         this[key] = jo[key];
     }
 }
Example #10
0
 public void Merge(IDictionary <string, object> dict)
 {
     // Purpose: Merge a dictionary into the current JObject
     // Author : Scott Bakker
     // Created: 02/11/2020
     // LastMod: 08/11/2020
     // Notes  : If any keys are duplicated, the new value overwrites the current value
     //        : This is processed one key/value at a time to trap errors.
     if (dict == null || dict.Count == 0)
     {
         return;
     }
     foreach (KeyValuePair <string, object> kv in dict)
     {
         if (JsonRoutines.IsWhitespaceString(kv.Key))
         {
             throw new SystemException(JsonKeyError);
         }
         this[kv.Key] = kv.Value;
     }
 }
Example #11
0
        internal static JObject Parse(CharReader reader)
        {
            // Purpose: Convert a partial string into a JObject
            // Author : Scott Bakker
            // Created: 09/13/2019
            // LastMod: 08/11/2020
            if (reader == null || reader.Peek() == -1)
            {
                return(null);
            }
            JObject result = new JObject();

            JsonRoutines.SkipBOM(reader);
            JsonRoutines.SkipWhitespace(reader);
            if (reader.Peek() != '{')
            {
                throw new SystemException(
                          $"JSON Error: Unexpected token to start JObject: {reader.Peek()}");
            }
            reader.Read();
            do
            {
                JsonRoutines.SkipWhitespace(reader);
                // check for symbols
                if (reader.Peek() == '}')
                {
                    reader.Read();
                    break; // done building JObject
                }
                if (reader.Peek() == ',')
                {
                    // this logic ignores extra commas, but is ok
                    reader.Read();
                    continue; // Next key/value
                }
                string tempKey = JsonRoutines.GetToken(reader);
                if (JsonRoutines.IsWhitespaceString(tempKey))
                {
                    throw new SystemException(JsonKeyError);
                }
                if (tempKey.Length <= 2 || !tempKey.StartsWith("\"") || !tempKey.EndsWith("\""))
                {
                    throw new SystemException($"JSON Error: Invalid key format: {tempKey}");
                }
                // Convert to usable key
                tempKey = JsonRoutines.JsonValueToObject(tempKey).ToString();
                if (JsonRoutines.IsWhitespaceString(tempKey.Substring(1, tempKey.Length - 2)))
                {
                    throw new SystemException(JsonKeyError);
                }
                // Check for ":" between key and value
                JsonRoutines.SkipWhitespace(reader);
                if (JsonRoutines.GetToken(reader) != ":")
                {
                    throw new SystemException($"JSON Error: Missing colon: {tempKey}");
                }
                // Get value
                JsonRoutines.SkipWhitespace(reader);
                if (reader.Peek() == '{') // JObject
                {
                    JObject jo = JObject.Parse(reader);
                    result[tempKey] = jo;
                    continue;
                }
                if (reader.Peek() == '[') // JArray
                {
                    JArray ja = JArray.Parse(reader);
                    result[tempKey] = ja;
                    continue;
                }
                // Get value as a string, convert to object
                string tempValue = JsonRoutines.GetToken(reader);
                result[tempKey] = JsonRoutines.JsonValueToObject(tempValue);
            } while (true);
            return(result);
        }
Example #12
0
 public object this[params string[] keys]
 {
     // Purpose: Give access to item values by key
     // Author : Scott Bakker
     // Created: 09/13/2019
     // LastMod: 08/14/2020
     get
     {
         JObject jo = this;
         int     i;
         // Follow the path specified in keys
         for (i = 0; i < keys.Length - 1; i++)
         {
             if (JsonRoutines.IsWhitespaceString(keys[i]))
             {
                 throw new ArgumentNullException(nameof(keys), JsonKeyError);
             }
             if (!jo._data.ContainsKey(keys[i]))
             {
                 return(null);
             }
             if (jo._data[keys[i]].GetType() != typeof(JObject))
             {
                 throw new ArgumentException($"Type is not JObject for \"{keys[i]}\": {jo._data[keys[i]].GetType()}");
             }
             jo = (JObject)jo._data[keys[i]];
         }
         // Get the value
         i = keys.Length - 1;
         if (JsonRoutines.IsWhitespaceString(keys[i]))
         {
             throw new ArgumentNullException(nameof(keys), JsonKeyError);
         }
         if (!jo._data.ContainsKey(keys[i]))
         {
             return(null);
         }
         return(jo._data[keys[i]]);
     }
     set
     {
         JObject jo = this;
         int     i;
         // Follow the path specified in keys
         for (i = 0; i < keys.Length - 1; i++)
         {
             if (JsonRoutines.IsWhitespaceString(keys[i]))
             {
                 throw new ArgumentNullException(nameof(keys), JsonKeyError);
             }
             if (!jo._data.ContainsKey(keys[i]))
             {
                 jo._data.Add(keys[i], new JObject());
             }
             else if (jo._data[keys[i]].GetType() != typeof(JObject))
             {
                 throw new ArgumentException($"Type is not JObject for \"{keys[i]}\": {jo._data[keys[i]].GetType()}");
             }
             jo = (JObject)jo._data[keys[i]];
         }
         // Add/update value
         i = keys.Length - 1;
         if (JsonRoutines.IsWhitespaceString(keys[i]))
         {
             throw new ArgumentNullException(nameof(keys), JsonKeyError);
         }
         if (!jo._data.ContainsKey(keys[i]))
         {
             jo._data.Add(keys[i], value);
         }
         else
         {
             jo._data[keys[i]] = value;
         }
     }
 }