private AssemblyCache GetAssemblyCache(Type classType, ISerializerSettings config) { if (_assemblyCache == null) { _assemblyCache = new Dictionary <Assembly, AssemblyCache>(); } AssemblyCache cache = null; if (!_assemblyCache.TryGetValue(classType.Assembly, out cache)) { cache = new AssemblyCache(classType.Assembly); foreach (JsonExDefaultValuesAttribute attr in classType.Assembly.GetCustomAttributes(typeof(JsonExDefaultValuesAttribute), false)) { if (attr.DefaultValueSetting != DefaultValueOption.InheritParentSetting) { cache.defaultOption = attr.DefaultValueSetting; } if (attr.Type != null) { if (cache.defaultValues == null) { cache.defaultValues = new DefaultValueCollection(config.DefaultValues); } cache.defaultValues[attr.Type] = attr.DefaultValue; } } if (cache.defaultOption == DefaultValueOption.InheritParentSetting && cache.defaultValues != null) { cache.defaultOption = DefaultValueOption.SuppressDefaultValues; } _assemblyCache[classType.Assembly] = cache; } return(cache); }
public override object ConvertFrom(object item, ISerializerSettings serializationContext) { _convertFromCount++; // seperate with ":" and surround with () this time MyImmutablePoint pt = (MyImmutablePoint)item; return("(" + pt.X + _separator + pt.Y + ")"); }
public static void SetConfigurationAware(object value, ISerializerSettings config) { IConfigurationAware contextAware = value as IConfigurationAware; if (contextAware != null) { contextAware.Settings = config; } }
public void WhenSuppressDefaultValuesOnProperty_ValueIsNotDefault_PropertyIsWritten(string propertyName, object value) { Serializer serializer = new Serializer(); ISerializerSettings config = serializer.Settings; IPropertyData property = config.Types[typeof(SimpleObject)].FindProperty(propertyName); property.DefaultValueSetting = DefaultValueOption.SuppressDefaultValues; Assert.IsTrue(property.ShouldWriteValue(config, value)); }
public CtorArgTypeResolver(ComplexExpressionBase expression, ISerializerSettings config, Type[] definedParameters) { if (expression == null) { throw new ArgumentNullException("Expression"); } _expression = expression; _definedParameters = definedParameters ?? new Type[0]; _config = config; }
public void WhenWriteAllValuesOnProperty_ValueIsDefault_PropertyWritten(string propertyName) { Serializer serializer = new Serializer(); ISerializerSettings config = serializer.Settings; IPropertyData property = config.Types[typeof(SimpleObject)].FindProperty(propertyName); SimpleObject testObject = new SimpleObject(); property.DefaultValueSetting = DefaultValueOption.WriteAllValues; Assert.IsTrue(property.ShouldWriteValue(config, property.GetValue(testObject))); }
public bool ShouldWriteValue(ISerializerSettings config, object value) { if (GetEffectiveDefaultValueSetting() == DefaultValueOption.SuppressDefaultValues) { return(!object.Equals(DefaultValue, value)); } else { return(true); } }
public override object ConvertTo(object item, Type sourceType, ISerializerSettings serializationContext) { string typeNameOrAlias = (string)item; Type typeResult = serializationContext.TypeAliases[typeNameOrAlias]; if (typeResult == null) { typeResult = Type.GetType(typeNameOrAlias); } return(typeResult); }
private static void CheckSettings(ISerializerSettings settings) { if (settings == null) { throw new ArgumentNullException(nameof(settings)); } if (string.IsNullOrWhiteSpace(settings.FilePath)) { throw new ArgumentException("File path can't be null, empty or white space"); } }
public TypeDataRepository(ISerializerSettings config) { _config = config; _cache = new Dictionary <Type, ITypeData>(); _attributeProcessors = new List <AttributeProcessor>(); _attributeProcessors.Add(new JsonIgnoreAttributeProcessor()); _attributeProcessors.Add(new JsonPropertyAttributeProcessor()); _attributeProcessors.Add(new JsonDefaultAttributeProcessor()); _attributeProcessors.Add(new ConstructorParameterAttributeProcessor()); _attributeProcessors.Add(new TypeConverterAttributeProcessor()); _attributeProcessors.Add(new JsonCollectionAttributeProcessor()); _propertyNamingStrategy = new DefaultPropertyNamingStrategy(); }
public override object ConvertTo(object item, Type sourceType, ISerializerSettings serializationContext) { string data = (string)item; if (data.IndexOf(',') != -1) { string[] splitData = data.Split(','); return(new MyImmutablePoint(int.Parse(splitData[0]), int.Parse(splitData[1]))); } else { return(new MyImmutablePoint(0, 0)); } }
private XmlConfigurator(XmlReader reader, ISerializerSettings serializerSettings, string sectionName) { this.reader = reader; this.serializerSettings = serializerSettings; this.sectionName = sectionName; handlers["IsCompact"] = delegate() { serializerSettings.IsCompact = reader.ReadElementContentAsBoolean(); }; handlers["OutputTypeInformation"] = delegate() { serializerSettings.OutputTypeInformation = reader.ReadElementContentAsBoolean(); }; handlers["ReferenceWritingType"] = new MapHandler(HandleReferenceWritingType); handlers["TypeBindings"] = new MapHandler(HandleTypeBindings); handlers["TypeConverters"] = new MapHandler(HandleTypeConverters); handlers["CollectionHandlers"] = new MapHandler(HandleCollectionHandlers); handlers["IgnoreProperties"] = new MapHandler(HandleIgnoreProperties); }
public override object ConvertTo(object item, Type sourceType, ISerializerSettings serializationContext) { _convertToCount++; string data = (string)item; if (data.IndexOf(_separator) != -1) { string[] splitData = data.Replace("(", "").Replace(")", "").Split(_separator.ToCharArray()); return(new MyImmutablePoint(int.Parse(splitData[0]), int.Parse(splitData[1]))); } else { return(new MyImmutablePoint(0, 0)); } }
public override object ConvertTo(object item, Type sourceType, ISerializerSettings serializationContext) { IDictionary dictionary = (IDictionary)Activator.CreateInstance(sourceType); ICollection coll = (ICollection)item; foreach (object colItem in coll) { IPropertyData propHandler = serializationContext.Types[colItem.GetType()].FindProperty(Context.ToString()); if (propHandler == null) { throw new MissingMemberException("Type: " + item.GetType().Name + " does not have an accessible property: " + Context); } dictionary[propHandler.GetValue(colItem)] = colItem; } return(dictionary); }
/// <summary> /// Resolves and updates the types of any constructor arguments /// </summary> /// <param name="context">serialization context</param> /// <param name="expression">object expression</param> protected static void ResolveConstructorTypes(ISerializerSettings settings, ObjectExpression expression) { ITypeData handler = settings.Types[expression.ResultType]; Type[] definedTypes = GetConstructorParameterTypes(handler.ConstructorParameters); CtorArgTypeResolver resolver = new CtorArgTypeResolver(expression, settings, definedTypes); Type[] resolvedTypes = resolver.ResolveTypes(); for (int i = 0; i < resolvedTypes.Length; i++) { if (resolvedTypes[i] != null) { expression.ConstructorArguments[i].ResultType = resolvedTypes[i]; } } }
public override object ConvertFrom(object item, ISerializerSettings serializationContext) { Type t = (Type)item; // TODO: Need a better way to get at this functionality StringWriter sw = new StringWriter(); TypeJsonWriter jw = new TypeJsonWriter(sw, false, serializationContext.TypeAliases); jw.WriteTypeInfo(t); StringBuilder sb = sw.GetStringBuilder(); if (sb.Length > 1 && sb[0] == '"' && sb[sb.Length - 1] == '"') { // remove double quotes sb.Remove(sb.Length - 1, 1); sb.Remove(0, 1); } return(sw.ToString()); }
/// <summary> /// Configures the <paramref name="serializerSettings"/> from the <paramref name="configSection"/> /// </summary> /// <param name="serializerSettings">an instance of serializer settings to configure</param> /// <param name="configSection">the name of a json serializer config section</param> public static void Configure(ISerializerSettings serializerSettings, string configSection) { XmlConfigSection section = (XmlConfigSection)ConfigurationManager.GetSection(configSection); if (section == null && configSection != "JsonExSerializer") { throw new ArgumentException("Unable to find config section " + configSection); } if (section == null) { return; } string xml = section.RawXml; XmlDocument doc = new XmlDocument(); doc.LoadXml(xml); Configure(serializerSettings, XmlReader.Create(new StringReader(xml)), configSection); }
public override object ConvertTo(object item, Type sourceType, ISerializerSettings serializationContext) { string bits = (string)((Hashtable)item)["Bits"]; int count = (int)((Hashtable)item)["Count"]; // >> 5 == Fast integer division by 32 int intLength = ((count - 1) >> 5) + 1; BitArray result = new BitArray(count); for (int i = 0, j = intLength - 1; i + 3 < bits.Length && j >= 0; i += 4, j--) { string temp = bits.Substring(i, 4); int value = int.Parse(temp, System.Globalization.NumberStyles.AllowHexSpecifier); int end = Math.Min(32, count - (j << 5)); for (int k = 0; k < end; k++) { result[j << 5 | k] = (value & (1 << k)) != 0; } } return result; }
/// converts a bit array into a string of the format: "63,FFEF10002EFA" /// length,HexEncodedBits public override object ConvertFrom(object item, ISerializerSettings serializationContext) { BitArray ba = (BitArray) item; int len = ba.Count; // set up our bits as int array int[] bits = new int[((len - 1) >> 5) + 1]; // copy the bool values to a temp array for iteration bool[] bitBools = new bool[len]; ba.CopyTo(bitBools, 0); // convert to int array for (int i = 0; i < len; i++) { if (bitBools[i]) { bits[i >> 5] |= 1 << i; } } // write as Hex values StringBuilder sb = new StringBuilder(4 * bits.Length); for (int i = bits.Length - 1; i >= 0; i--) { string formatted = bits[i].ToString("X"); if (bits[i] < 4096) // minimum value that is 4-digits { sb.Append(formatted.PadLeft(4, '0')); } else { sb.Append(formatted); } } Hashtable result = new Hashtable(); result["Count"] = len; result["Bits"] = sb.ToString(); return result; }
protected virtual CollectionHandler ConstructOrFindHandler(ISerializerSettings config, Type collHandlerType, ref bool handlerConstructed) { handlerConstructed = false; CollectionHandler handler = config.CollectionHandlers.Find(delegate(CollectionHandler h) { return(h.GetType() == collHandlerType); }); if (handler != null) { return(handler); } // try inherited type next handler = config.CollectionHandlers.Find(delegate(CollectionHandler h) { return(collHandlerType.IsInstanceOfType(h)); }); if (handler != null) { return(handler); } // create the handler handler = (CollectionHandler)Activator.CreateInstance(collHandlerType); handlerConstructed = true; return(handler); }
public CtorArgTypeResolver(ComplexExpressionBase expression, ISerializerSettings config) : this(expression, config, new Type[0]) { }
public void Setup() { serializer = new Serializer("SimpleSettingsConfig"); context = serializer.Settings; }
public override void Process(IMetaData metaData, ICustomAttributeProvider attributeProvider, ISerializerSettings config) { if (metaData is IPropertyData) { IPropertyData property = (IPropertyData)metaData; JsonExDefaultAttribute defaultAttr = ReflectionUtils.GetAttribute <JsonExDefaultAttribute>(attributeProvider, false); if (defaultAttr != null) { switch (defaultAttr.DefaultValueSetting) { case DefaultValueOption.InheritParentSetting: case DefaultValueOption.SuppressDefaultValues: property.DefaultValueSetting = defaultAttr.DefaultValueSetting; if (defaultAttr.DefaultValueSet) { property.DefaultValue = defaultAttr.DefaultValue; } break; case DefaultValueOption.WriteAllValues: property.DefaultValueSetting = defaultAttr.DefaultValueSetting; break; } } } else if (metaData is TypeData) { Type classType = metaData.ForType; TypeData typeData = (TypeData)metaData; // apply assembly defaults first AssemblyCache cache = GetAssemblyCache(classType, config); if (cache.defaultValues != null) { typeData.DefaultValues = new DefaultValueCollection(cache.defaultValues); } if (cache.defaultOption != DefaultValueOption.InheritParentSetting) { typeData.DefaultValueSetting = cache.defaultOption; } bool typeSet = false; foreach (JsonExDefaultValuesAttribute attr in attributeProvider.GetCustomAttributes(typeof(JsonExDefaultValuesAttribute), false)) { if (attr.DefaultValueSetting != DefaultValueOption.InheritParentSetting) { typeData.DefaultValueSetting = attr.DefaultValueSetting; } if (attr.Type != null) { typeData.DefaultValues[attr.Type] = attr.DefaultValue; typeSet = true; } } if (typeData.DefaultValueSetting == DefaultValueOption.InheritParentSetting && typeSet) { typeData.DefaultValueSetting = DefaultValueOption.SuppressDefaultValues; } } }
public override object ConvertTo(object item, Type sourceType, ISerializerSettings serializationContext) { return(Activator.CreateInstance(sourceType, item)); }
public override object ConvertFrom(object item, ISerializerSettings serializationContext) { return(item.ToString()); }
public override void Process(IMetaData metaData, ICustomAttributeProvider attributeProvider, ISerializerSettings config) { if (metaData is IPropertyData) { IPropertyData property = (IPropertyData)metaData; JsonExPropertyAttribute attr = ReflectionUtils.GetAttribute <JsonExPropertyAttribute>(attributeProvider, false); if (attr != null) { property.Ignored = false; if (!string.IsNullOrEmpty(attr.Alias)) { property.Alias = attr.Alias; } } } }
public override void Process(IMetaData metaData, ICustomAttributeProvider attributeProvider, ISerializerSettings config) { if (metaData is IPropertyData) { IPropertyData property = (IPropertyData)metaData; if (attributeProvider.IsDefined(typeof(XmlIgnoreAttribute), false)) property.Ignored = true; } }
public override void Process(IMetaData metaData, ICustomAttributeProvider attributeProvider, ISerializerSettings config) { IJsonTypeConverter converter = CreateTypeConverter(attributeProvider); if (converter != null) { metaData.TypeConverter = converter; } }
public override void Process(IMetaData metaData, ICustomAttributeProvider attributeProvider, ISerializerSettings config) { TypeData typeData = metaData as TypeData; if (typeData == null) { return; } JsonExCollectionAttribute attr = ReflectionUtils.GetAttribute <JsonExCollectionAttribute>(attributeProvider, true); if (attr == null) { return; } if (!attr.IsValid()) { throw new Exception("Invalid JsonExCollectionAttribute specified for " + attributeProvider + ", either CollectionHandlerType or ItemType or both must be specified"); } Type collHandlerType = attr.GetCollectionHandlerType(); Type itemType = attr.GetItemType(); // Try exact type match first CollectionHandler handler = null; if (collHandlerType == null) { handler = typeData.FindCollectionHandler(); handler = new CollectionHandlerWrapper(handler, typeData.ForType, itemType); } bool registerHandler = false; if (handler == null) { handler = ConstructOrFindHandler(config, collHandlerType, ref registerHandler); } typeData.CollectionHandler = handler; // install the handler if (registerHandler) { config.RegisterCollectionHandler(handler); } }
public JsonSerializer(ISerializerSettings settings) : base(settings) => serializer = new JavaScriptSerializer();