#region License // Copyright (c) 2007 James Newton-King // // Permission is hereby granted, free of charge, to any person // obtaining a copy of this software and associated documentation // files (the "Software"), to deal in the Software without // restriction, including without limitation the rights to use, // copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following // conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR // OTHER DEALINGS IN THE SOFTWARE. #endregion using System; using System.Collections.Generic; using System.Collections.ObjectModel; #if !PORTABLE40 using System.Collections.Specialized; #endif using System.ComponentModel; #if !(NET35 || NET20 || PORTABLE40) using System.Dynamic; using System.Linq.Expressions; #endif using System.IO; using Newtonsoft.Json.Utilities; using System.Globalization; #if NET20 using Newtonsoft.Json.Utilities.LinqBridge; #else using System.Linq; #endif namespace Newtonsoft.Json.Linq { /// /// Represents a JSON object. /// /// /// /// public class JObject : JContainer, IDictionary, INotifyPropertyChanged #if !(DOTNET || PORTABLE40 || PORTABLE) , ICustomTypeDescriptor #endif #if !(NET20 || PORTABLE40 || PORTABLE) , INotifyPropertyChanging #endif { private readonly JPropertyKeyedCollection _properties = new JPropertyKeyedCollection(); /// /// Gets the container's children tokens. /// /// The container's children tokens. protected override IList ChildrenTokens { get { return _properties; } } /// /// Occurs when a property value changes. /// public event PropertyChangedEventHandler PropertyChanged; #if !(NET20 || PORTABLE || PORTABLE40) /// /// Occurs when a property value is changing. /// public event PropertyChangingEventHandler PropertyChanging; #endif /// /// Initializes a new instance of the class. /// public JObject() { } /// /// Initializes a new instance of the class from another object. /// /// A object to copy from. public JObject(JObject other) : base(other) { } /// /// Initializes a new instance of the class with the specified content. /// /// The contents of the object. public JObject(params object[] content) : this((object)content) { } /// /// Initializes a new instance of the class with the specified content. /// /// The contents of the object. public JObject(object content) { Add(content); } internal override bool DeepEquals(JToken node) { JObject t = node as JObject; if (t == null) { return false; } return _properties.Compare(t._properties); } internal override void InsertItem(int index, JToken item, bool skipParentCheck) { // don't add comments to JObject, no name to reference comment by if (item != null && item.Type == JTokenType.Comment) { return; } base.InsertItem(index, item, skipParentCheck); } internal override void ValidateToken(JToken o, JToken existing) { ValidationUtils.ArgumentNotNull(o, nameof(o)); if (o.Type != JTokenType.Property) { throw new ArgumentException("Can not add {0} to {1}.".FormatWith(CultureInfo.InvariantCulture, o.GetType(), GetType())); } JProperty newProperty = (JProperty)o; if (existing != null) { JProperty existingProperty = (JProperty)existing; if (newProperty.Name == existingProperty.Name) { return; } } if (_properties.TryGetValue(newProperty.Name, out existing)) { throw new ArgumentException("Can not add property {0} to {1}. Property with the same name already exists on object.".FormatWith(CultureInfo.InvariantCulture, newProperty.Name, GetType())); } } internal override void MergeItem(object content, JsonMergeSettings settings) { JObject o = content as JObject; if (o == null) { return; } foreach (KeyValuePair contentItem in o) { JProperty existingProperty = Property(contentItem.Key); if (existingProperty == null) { Add(contentItem.Key, contentItem.Value); } else if (contentItem.Value != null) { JContainer existingContainer = existingProperty.Value as JContainer; if (existingContainer == null) { if (contentItem.Value.Type != JTokenType.Null || settings?.MergeNullValueHandling == MergeNullValueHandling.Merge) { existingProperty.Value = contentItem.Value; } } else if (existingContainer.Type != contentItem.Value.Type) { existingProperty.Value = contentItem.Value; } else { existingContainer.Merge(contentItem.Value, settings); } } } } internal void InternalPropertyChanged(JProperty childProperty) { OnPropertyChanged(childProperty.Name); #if !(DOTNET || PORTABLE40 || PORTABLE) if (_listChanged != null) { OnListChanged(new ListChangedEventArgs(ListChangedType.ItemChanged, IndexOfItem(childProperty))); } #endif #if !(NET20 || NET35 || PORTABLE40) if (_collectionChanged != null) { OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Replace, childProperty, childProperty, IndexOfItem(childProperty))); } #endif } internal void InternalPropertyChanging(JProperty childProperty) { #if !(NET20 || PORTABLE40 || PORTABLE) OnPropertyChanging(childProperty.Name); #endif } internal override JToken CloneToken() { return new JObject(this); } /// /// Gets the node type for this . /// /// The type. public override JTokenType Type { get { return JTokenType.Object; } } /// /// Gets an of this object's properties. /// /// An of this object's properties. public IEnumerable Properties() { return _properties.Cast(); } /// /// Gets a the specified name. /// /// The property name. /// A with the specified name or null. public JProperty Property(string name) { if (name == null) { return null; } JToken property; _properties.TryGetValue(name, out property); return (JProperty)property; } /// /// Gets an of this object's property values. /// /// An of this object's property values. public JEnumerable PropertyValues() { return new JEnumerable(Properties().Select(p => p.Value)); } /// /// Gets the with the specified key. /// /// The with the specified key. public override JToken this[object key] { get { ValidationUtils.ArgumentNotNull(key, nameof(key)); string propertyName = key as string; if (propertyName == null) { throw new ArgumentException("Accessed JObject values with invalid key value: {0}. Object property name expected.".FormatWith(CultureInfo.InvariantCulture, MiscellaneousUtils.ToString(key))); } return this[propertyName]; } set { ValidationUtils.ArgumentNotNull(key, nameof(key)); string propertyName = key as string; if (propertyName == null) { throw new ArgumentException("Set JObject values with invalid key value: {0}. Object property name expected.".FormatWith(CultureInfo.InvariantCulture, MiscellaneousUtils.ToString(key))); } this[propertyName] = value; } } /// /// Gets or sets the with the specified property name. /// /// public JToken this[string propertyName] { get { ValidationUtils.ArgumentNotNull(propertyName, nameof(propertyName)); JProperty property = Property(propertyName); return (property != null) ? property.Value : null; } set { JProperty property = Property(propertyName); if (property != null) { property.Value = value; } else { #if !(NET20 || PORTABLE40 || PORTABLE) OnPropertyChanging(propertyName); #endif Add(new JProperty(propertyName, value)); OnPropertyChanged(propertyName); } } } /// /// Loads an from a . /// /// A that will be read for the content of the . /// A that contains the JSON that was read from the specified . public new static JObject Load(JsonReader reader) { return Load(reader, null); } /// /// Loads an from a . /// /// A that will be read for the content of the . /// The used to load the JSON. /// If this is null, default load settings will be used. /// A that contains the JSON that was read from the specified . public new static JObject Load(JsonReader reader, JsonLoadSettings settings) { ValidationUtils.ArgumentNotNull(reader, nameof(reader)); if (reader.TokenType == JsonToken.None) { if (!reader.Read()) { throw JsonReaderException.Create(reader, "Error reading JObject from JsonReader."); } } reader.MoveToContent(); if (reader.TokenType != JsonToken.StartObject) { throw JsonReaderException.Create(reader, "Error reading JObject from JsonReader. Current JsonReader item is not an object: {0}".FormatWith(CultureInfo.InvariantCulture, reader.TokenType)); } JObject o = new JObject(); o.SetLineInfo(reader as IJsonLineInfo, settings); o.ReadTokenFrom(reader, settings); return o; } /// /// Load a from a string that contains JSON. /// /// A that contains JSON. /// A populated from the string that contains JSON. /// /// /// public new static JObject Parse(string json) { return Parse(json, null); } /// /// Load a from a string that contains JSON. /// /// A that contains JSON. /// The used to load the JSON. /// If this is null, default load settings will be used. /// A populated from the string that contains JSON. /// /// /// public new static JObject Parse(string json, JsonLoadSettings settings) { using (JsonReader reader = new JsonTextReader(new StringReader(json))) { JObject o = Load(reader, settings); if (reader.Read() && reader.TokenType != JsonToken.Comment) { throw JsonReaderException.Create(reader, "Additional text found in JSON string after parsing content."); } return o; } } /// /// Creates a from an object. /// /// The object that will be used to create . /// A with the values of the specified object public new static JObject FromObject(object o) { return FromObject(o, JsonSerializer.CreateDefault()); } /// /// Creates a from an object. /// /// The object that will be used to create . /// The that will be used to read the object. /// A with the values of the specified object public new static JObject FromObject(object o, JsonSerializer jsonSerializer) { JToken token = FromObjectInternal(o, jsonSerializer); if (token != null && token.Type != JTokenType.Object) { throw new ArgumentException("Object serialized to {0}. JObject instance expected.".FormatWith(CultureInfo.InvariantCulture, token.Type)); } return (JObject)token; } /// /// Writes this token to a . /// /// A into which this method will write. /// A collection of which will be used when writing the token. public override void WriteTo(JsonWriter writer, params JsonConverter[] converters) { writer.WriteStartObject(); for (int i = 0; i < _properties.Count; i++) { _properties[i].WriteTo(writer, converters); } writer.WriteEndObject(); } /// /// Gets the with the specified property name. /// /// Name of the property. /// The with the specified property name. public JToken GetValue(string propertyName) { return GetValue(propertyName, StringComparison.Ordinal); } /// /// Gets the with the specified property name. /// The exact property name will be searched for first and if no matching property is found then /// the will be used to match a property. /// /// Name of the property. /// One of the enumeration values that specifies how the strings will be compared. /// The with the specified property name. public JToken GetValue(string propertyName, StringComparison comparison) { if (propertyName == null) { return null; } // attempt to get value via dictionary first for performance JProperty property = Property(propertyName); if (property != null) { return property.Value; } // test above already uses this comparison so no need to repeat if (comparison != StringComparison.Ordinal) { foreach (JProperty p in _properties) { if (string.Equals(p.Name, propertyName, comparison)) { return p.Value; } } } return null; } /// /// Tries to get the with the specified property name. /// The exact property name will be searched for first and if no matching property is found then /// the will be used to match a property. /// /// Name of the property. /// The value. /// One of the enumeration values that specifies how the strings will be compared. /// true if a value was successfully retrieved; otherwise, false. public bool TryGetValue(string propertyName, StringComparison comparison, out JToken value) { value = GetValue(propertyName, comparison); return (value != null); } #region IDictionary Members /// /// Adds the specified property name. /// /// Name of the property. /// The value. public void Add(string propertyName, JToken value) { Add(new JProperty(propertyName, value)); } bool IDictionary.ContainsKey(string key) { return _properties.Contains(key); } ICollection IDictionary.Keys { // todo: make order the collection returned match JObject order get { return _properties.Keys; } } /// /// Removes the property with the specified name. /// /// Name of the property. /// true if item was successfully removed; otherwise, false. public bool Remove(string propertyName) { JProperty property = Property(propertyName); if (property == null) { return false; } property.Remove(); return true; } /// /// Tries the get value. /// /// Name of the property. /// The value. /// true if a value was successfully retrieved; otherwise, false. public bool TryGetValue(string propertyName, out JToken value) { JProperty property = Property(propertyName); if (property == null) { value = null; return false; } value = property.Value; return true; } ICollection IDictionary.Values { get { // todo: need to wrap _properties.Values with a collection to get the JProperty value throw new NotImplementedException(); } } #endregion #region ICollection> Members void ICollection>.Add(KeyValuePair item) { Add(new JProperty(item.Key, item.Value)); } void ICollection>.Clear() { RemoveAll(); } bool ICollection>.Contains(KeyValuePair item) { JProperty property = Property(item.Key); if (property == null) { return false; } return (property.Value == item.Value); } void ICollection>.CopyTo(KeyValuePair[] array, int arrayIndex) { if (array == null) { throw new ArgumentNullException(nameof(array)); } if (arrayIndex < 0) { throw new ArgumentOutOfRangeException(nameof(arrayIndex), "arrayIndex is less than 0."); } if (arrayIndex >= array.Length && arrayIndex != 0) { throw new ArgumentException("arrayIndex is equal to or greater than the length of array."); } if (Count > array.Length - arrayIndex) { throw new ArgumentException("The number of elements in the source JObject is greater than the available space from arrayIndex to the end of the destination array."); } int index = 0; foreach (JProperty property in _properties) { array[arrayIndex + index] = new KeyValuePair(property.Name, property.Value); index++; } } bool ICollection>.IsReadOnly { get { return false; } } bool ICollection>.Remove(KeyValuePair item) { if (!((ICollection>)this).Contains(item)) { return false; } ((IDictionary)this).Remove(item.Key); return true; } #endregion internal override int GetDeepHashCode() { return ContentsHashCode(); } /// /// Returns an enumerator that iterates through the collection. /// /// /// A that can be used to iterate through the collection. /// public IEnumerator> GetEnumerator() { foreach (JProperty property in _properties) { yield return new KeyValuePair(property.Name, property.Value); } } /// /// Raises the event with the provided arguments. /// /// Name of the property. protected virtual void OnPropertyChanged(string propertyName) { if (PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); } } #if !(PORTABLE40 || PORTABLE || NET20) /// /// Raises the event with the provided arguments. /// /// Name of the property. protected virtual void OnPropertyChanging(string propertyName) { if (PropertyChanging != null) { PropertyChanging(this, new PropertyChangingEventArgs(propertyName)); } } #endif #if !(DOTNET || PORTABLE40 || PORTABLE) // include custom type descriptor on JObject rather than use a provider because the properties are specific to a type #region ICustomTypeDescriptor /// /// Returns the properties for this instance of a component. /// /// /// A that represents the properties for this component instance. /// PropertyDescriptorCollection ICustomTypeDescriptor.GetProperties() { return ((ICustomTypeDescriptor)this).GetProperties(null); } /// /// Returns the properties for this instance of a component using the attribute array as a filter. /// /// An array of type that is used as a filter. /// /// A that represents the filtered properties for this component instance. /// PropertyDescriptorCollection ICustomTypeDescriptor.GetProperties(Attribute[] attributes) { PropertyDescriptorCollection descriptors = new PropertyDescriptorCollection(null); foreach (KeyValuePair propertyValue in this) { descriptors.Add(new JPropertyDescriptor(propertyValue.Key)); } return descriptors; } /// /// Returns a collection of custom attributes for this instance of a component. /// /// /// An containing the attributes for this object. /// AttributeCollection ICustomTypeDescriptor.GetAttributes() { return AttributeCollection.Empty; } /// /// Returns the class name of this instance of a component. /// /// /// The class name of the object, or null if the class does not have a name. /// string ICustomTypeDescriptor.GetClassName() { return null; } /// /// Returns the name of this instance of a component. /// /// /// The name of the object, or null if the object does not have a name. /// string ICustomTypeDescriptor.GetComponentName() { return null; } /// /// Returns a type converter for this instance of a component. /// /// /// A that is the converter for this object, or null if there is no for this object. /// TypeConverter ICustomTypeDescriptor.GetConverter() { return new TypeConverter(); } /// /// Returns the default event for this instance of a component. /// /// /// An that represents the default event for this object, or null if this object does not have events. /// EventDescriptor ICustomTypeDescriptor.GetDefaultEvent() { return null; } /// /// Returns the default property for this instance of a component. /// /// /// A that represents the default property for this object, or null if this object does not have properties. /// PropertyDescriptor ICustomTypeDescriptor.GetDefaultProperty() { return null; } /// /// Returns an editor of the specified type for this instance of a component. /// /// A that represents the editor for this object. /// /// An of the specified type that is the editor for this object, or null if the editor cannot be found. /// object ICustomTypeDescriptor.GetEditor(Type editorBaseType) { return null; } /// /// Returns the events for this instance of a component using the specified attribute array as a filter. /// /// An array of type that is used as a filter. /// /// An that represents the filtered events for this component instance. /// EventDescriptorCollection ICustomTypeDescriptor.GetEvents(Attribute[] attributes) { return EventDescriptorCollection.Empty; } /// /// Returns the events for this instance of a component. /// /// /// An that represents the events for this component instance. /// EventDescriptorCollection ICustomTypeDescriptor.GetEvents() { return EventDescriptorCollection.Empty; } /// /// Returns an object that contains the property described by the specified property descriptor. /// /// A that represents the property whose owner is to be found. /// /// An that represents the owner of the specified property. /// object ICustomTypeDescriptor.GetPropertyOwner(PropertyDescriptor pd) { return null; } #endregion #endif #if !(NET35 || NET20 || PORTABLE40) /// /// Returns the responsible for binding operations performed on this object. /// /// The expression tree representation of the runtime value. /// /// The to bind this object. /// protected override DynamicMetaObject GetMetaObject(Expression parameter) { return new DynamicProxyMetaObject(parameter, this, new JObjectDynamicProxy(), true); } private class JObjectDynamicProxy : DynamicProxy { public override bool TryGetMember(JObject instance, GetMemberBinder binder, out object result) { // result can be null result = instance[binder.Name]; return true; } public override bool TrySetMember(JObject instance, SetMemberBinder binder, object value) { JToken v = value as JToken; // this can throw an error if value isn't a valid for a JValue if (v == null) { v = new JValue(value); } instance[binder.Name] = v; return true; } public override IEnumerable GetDynamicMemberNames(JObject instance) { return instance.Properties().Select(p => p.Name); } } #endif } }