Esempio n. 1
0
        public static JToken SerializeToJToken(this JsonSerializer serializer, object value)
        {
            Type vt = value != null?value.GetType() : typeof(object);

            var convName = GetTypeConverterName(vt);
            var conv     = serializer.Converters.Where(c => c.GetType().Name == convName || (c.GetType().IsGenericType&& c.GetType().GetGenericArguments()[0] == vt)).FirstOrDefault();

            if (conv == null && ChoJSONConvertersCache.IsInitialized)
            {
                if (ChoJSONConvertersCache.Contains(convName))
                {
                    conv = ChoJSONConvertersCache.Get(convName);
                }
            }

            JToken t = null;

            if (conv == null)
            {
                t = JToken.FromObject(value, serializer);
            }
            else
            {
                t = JToken.Parse(JsonConvert.SerializeObject(value, serializer.Formatting, conv));
            }
            return(t);
        }
Esempio n. 2
0
        public static object DeserializeObject(this JsonSerializer serializer, JsonReader reader, Type objType)
        {
            var convName = GetTypeConverterName(objType);
            var conv     = serializer.Converters.Where(c => c.GetType().Name == convName || (c.GetType().IsGenericType&& c.GetType().GetGenericArguments()[0] == objType)).FirstOrDefault();

            if (conv == null && ChoJSONConvertersCache.IsInitialized)
            {
                if (ChoJSONConvertersCache.Contains(convName))
                {
                    conv = ChoJSONConvertersCache.Get(convName);
                }
            }

            JToken t = null;

            if (conv == null)
            {
                return(serializer.Deserialize(reader, objType));
            }
            else
            {
                return(JsonConvert.DeserializeObject(JObject.ReadFrom(reader).ToString(), objType, conv));
            }
        }
 public ChoJSONRecordConfiguration WithJSONConverter(JsonConverter converter)
 {
     ChoJSONConvertersCache.Add(converter);
     return(this);
 }
        public override void Validate(object state)
        {
            if (TurnOnAutoDiscoverJsonConverters)
            {
                ChoJSONConvertersCache.Init();
            }

            if (_jsonSerializerSettings != null)
            {
                foreach (var conv in GetJSONConverters())
                {
                    _jsonSerializerSettings.Converters.Add(conv);
                }
                foreach (var conv in _jsonSerializerSettings.Converters.OfType <IChoJSONConverter>())
                {
                    conv.Serializer            = JsonSerializer;
                    conv.Context               = new ChoDynamicObject();
                    conv.Context.Configuration = this;
                }
                foreach (var conv in _jsonSerializerSettings.Converters)
                {
                    JsonSerializer.Converters.Add(conv);
                }
            }

            if (RecordType != null)
            {
                Init(RecordType);
            }

            base.Validate(state);

            string[] fieldNames = null;
            JObject  jObject    = null;

            if (state is Tuple <long, JObject> )
            {
                jObject = ((Tuple <long, JObject>)state).Item2;
            }
            else
            {
                fieldNames = state as string[];
            }

            if (fieldNames != null && JSONRecordFieldConfigurations.Count > 0 && FlattenNode)
            {
                JSONRecordFieldConfigurations.Clear();
            }

            if (AutoDiscoverColumns &&
                JSONRecordFieldConfigurations.Count == 0)
            {
                if (RecordType != null && !IsDynamicObject && /*&& RecordType != typeof(ExpandoObject)*/
                    ChoTypeDescriptor.GetProperties(RecordType).Where(pd => pd.Attributes.OfType <ChoJSONRecordFieldAttribute>().Any()).Any())
                {
                    MapRecordFields(RecordType);
                }
                else if (jObject != null)
                {
                    Dictionary <string, ChoJSONRecordFieldConfiguration> dict = new Dictionary <string, ChoJSONRecordFieldConfiguration>(StringComparer.CurrentCultureIgnoreCase);
                    string name = null;
                    foreach (var attr in jObject.Properties())
                    {
                        name = attr.Name;
                        if (!dict.ContainsKey(name))
                        {
                            dict.Add(name, new ChoJSONRecordFieldConfiguration(name, (string)null));
                        }
                        else
                        {
                            throw new ChoRecordConfigurationException("Duplicate field(s) [Name(s): {0}] found.".FormatString(name));
                        }
                    }

                    foreach (ChoJSONRecordFieldConfiguration obj in dict.Values)
                    {
                        JSONRecordFieldConfigurations.Add(obj);
                    }
                }
                else if (!fieldNames.IsNullOrEmpty())
                {
                    foreach (string fn in fieldNames)
                    {
                        if (IgnoredFields.Contains(fn))
                        {
                            continue;
                        }

                        var obj = new ChoJSONRecordFieldConfiguration(fn, (string)null);
                        JSONRecordFieldConfigurations.Add(obj);
                    }
                }
            }
            else
            {
                foreach (var fc in JSONRecordFieldConfigurations)
                {
                    fc.ComplexJPathUsed = !(fc.JSONPath.IsNullOrWhiteSpace() || String.Compare(fc.FieldName, fc.JSONPath, true) == 0);
                }
            }

            //if (JSONRecordFieldConfigurations.Count <= 0)
            //    throw new ChoRecordConfigurationException("No record fields specified.");

            //Validate each record field
            foreach (var fieldConfig in JSONRecordFieldConfigurations)
            {
                fieldConfig.Validate(this);
            }

            //Check field position for duplicate
            string[] dupFields = JSONRecordFieldConfigurations.GroupBy(i => i.FieldName)
                                 .Where(g => g.Count() > 1)
                                 .Select(g => g.Key).ToArray();

            if (dupFields.Length > 0)
            {
                throw new ChoRecordConfigurationException("Duplicate field(s) [Name(s): {0}] found.".FormatString(String.Join(",", dupFields)));
            }

            PIDict = new Dictionary <string, System.Reflection.PropertyInfo>(StringComparer.InvariantCultureIgnoreCase);
            PDDict = new Dictionary <string, PropertyDescriptor>(StringComparer.InvariantCultureIgnoreCase);
            foreach (var fc in JSONRecordFieldConfigurations)
            {
                var pd1 = fc.DeclaringMember.IsNullOrWhiteSpace() ? ChoTypeDescriptor.GetProperty(RecordType, fc.Name)
                    : ChoTypeDescriptor.GetProperty(RecordType, fc.DeclaringMember);
                if (pd1 != null)
                {
                    fc.PropertyDescriptor = pd1;
                }

                if (fc.PropertyDescriptor == null)
                {
                    fc.PropertyDescriptor = TypeDescriptor.GetProperties(RecordType).AsTypedEnumerable <PropertyDescriptor>().Where(pd => pd.Name == fc.Name).FirstOrDefault();
                }
                if (fc.PropertyDescriptor == null)
                {
                    continue;
                }

                PIDict.Add(fc.Name, fc.PropertyDescriptor.ComponentType.GetProperty(fc.PropertyDescriptor.Name));
                PDDict.Add(fc.Name, fc.PropertyDescriptor);
            }

            RecordFieldConfigurationsDict = JSONRecordFieldConfigurations.Where(i => !i.Name.IsNullOrWhiteSpace()).ToDictionary(i => i.Name);

            LoadNCacheMembers(JSONRecordFieldConfigurations);
        }
Esempio n. 5
0
        public static JToken SerializeToJToken(this JsonSerializer serializer, object value, Formatting?formatting = null, JsonSerializerSettings settings = null,
                                               bool dontUseConverter = false, bool enableXmlAttributePrefix = false)
        {
            JsonConverter conv = null;

            if (!dontUseConverter)
            {
                Type vt = value != null?value.GetType() : typeof(object);

                var convName = GetTypeConverterName(vt);
                conv = serializer.Converters.Where(c => c.GetType().Name == convName || (c.GetType().IsGenericType&& c.GetType().GetGenericArguments()[0] == vt)).FirstOrDefault();
                if (conv == null && ChoJSONConvertersCache.IsInitialized)
                {
                    if (ChoJSONConvertersCache.Contains(convName))
                    {
                        conv = ChoJSONConvertersCache.Get(convName);
                    }
                    else if (ChoJSONConvertersCache.Contains(vt))
                    {
                        conv = ChoJSONConvertersCache.Get(vt);
                    }
                }
            }

            if (value != null)
            {
                if (!value.GetType().IsSimple())
                {
                    bool disableImplcityOp = false;
                    if (ChoTypeDescriptor.GetTypeAttribute <ChoTurnOffImplicitOpsAttribute>(value.GetType()) != null)
                    {
                        disableImplcityOp = ChoTypeDescriptor.GetTypeAttribute <ChoTurnOffImplicitOpsAttribute>(value.GetType()).Flag;
                    }

                    if (!disableImplcityOp)
                    {
                        Type to = null;
                        if (value.GetType().CanCastToPrimitiveType(out to))
                        {
                            value = ChoConvert.ConvertTo(value, to);
                        }
                        else if (value.GetType().GetImplicitTypeCastBackOps().Any())
                        {
                            var castTypes = value.GetType().GetImplicitTypeCastBackOps();

                            foreach (var ct in castTypes)
                            {
                                try
                                {
                                    value = ChoConvert.ConvertTo(value, ct);
                                    break;
                                }
                                catch { }
                            }
                        }
                    }
                }
            }

            JToken t = null;

            if (settings != null)
            {
                if (conv != null)
                {
                    settings.Converters.Add(conv);
                }
            }
            if (formatting == null)
            {
                formatting = serializer.Formatting;
            }

            if (settings != null && settings.Context.Context == null && enableXmlAttributePrefix)
            {
                settings.Context = new System.Runtime.Serialization.StreamingContext(System.Runtime.Serialization.StreamingContextStates.All, new ChoDynamicObject());
                dynamic ctx = settings.Context.Context;
                ctx.EnableXmlAttributePrefix = enableXmlAttributePrefix;
            }

            if (conv != null)
            {
                t = JToken.Parse(JsonConvert.SerializeObject(value, formatting.Value, conv));
            }
            else if (settings != null)
            {
                t = JToken.Parse(JsonConvert.SerializeObject(value, formatting.Value, settings));
            }
            else
            {
                t = JToken.FromObject(value, serializer);
            }
            return(t);
        }