Populate() публичный Метод

Populates the JSON values onto the target object.
public Populate ( JsonReader reader, object target ) : void
reader JsonReader The that contains the JSON structure to reader values from.
target object The target object to populate values onto.
Результат void
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue,
            JsonSerializer serializer)
        {
            JObject o = JObject.Load(reader);

            var prop = o.Properties().First();
            var key = prop.Name;
            switch (key)
            {
                case "delete":
                    var deleteItem = new BulkDeleteResponseItem();
                    serializer.Populate(prop.Value.CreateReader(), deleteItem);
                    if (deleteItem != null)
                        deleteItem.Operation = key;
                    return deleteItem;
                case "index":
                    var indexItem = new BulkIndexResponseItem();
                    serializer.Populate(prop.Value.CreateReader(), indexItem);
                    if (indexItem != null)
                        indexItem.Operation = key;
                    return indexItem;
                case "create":
                    var createItem = new BulkCreateResponseItem();
                    serializer.Populate(prop.Value.CreateReader(), createItem);
                    if (createItem != null)
                        createItem.Operation = key;
                    return createItem;
            }
            return null;
        }
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            var json = JObject.Load(reader);

            var config = new SensuClientConfig();
            serializer.Populate(json.CreateReader(), config);

            if (!Directory.Exists(_configDir)) return config;

            foreach (var configFile in Directory.GetFiles(_configDir, "*.json"))
            {
                try {
                    using (var envReader = new StreamReader(configFile))
                    {
                        using (var envJsonReader = new JsonTextReader(envReader))
                        {
                            serializer.Populate(envJsonReader, config);
                        }
                    }
                }
                catch (Exception e)
                {
                    Log.Warn("File {0} has some errors and won't be ignored: {1}", configFile, e);
                }
            }

            return config;
        }
Пример #3
0
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            JObject json = JObject.Load(reader);

            var config = new AsimovConfig();
            serializer.Populate(json.CreateReader(), config);

            var self = GetSelf(json);
            if (self != null)
            {
                serializer.Populate(self.CreateReader(), config);
            }
            else
            {
                Log.ErrorFormat("Could not find agent specific config / environment for: {0}", _machineName);
            }

            var envConfigFile = Path.Combine(_configDir, string.Format("config.{0}.json", config.Environment));

            if (!File.Exists(envConfigFile))
                return config;

            Log.DebugFormat("Loading config file {0}", envConfigFile);

            using (var envReader = new StreamReader(envConfigFile))
            {
                using (var envJsonReader = new JsonTextReader(envReader))
                {
                    serializer.Populate(envJsonReader, config);
                }
            }

            return config;
        }
        public override object ReadJson(
            JsonReader reader,
            Type objectType,
            object existingValue,
            Newtonsoft.Json.JsonSerializer serializer)
        {
            JObject             jObject  = JObject.Load(reader);
            GetScheduleResponse response = new GetScheduleResponse();

            foreach (var node in jObject)
            {
                if (node.Value != null && Enum.TryParse(node.Key, out Currency currency))
                {
                    CurrencySchedule currencySchedule = new CurrencySchedule();
                    serializer.Populate(node.Value.CreateReader(), currencySchedule);
                    response.Currency =
                        new Dictionary <Currency, CurrencySchedule> {
                        { currency, currencySchedule }
                    };
                }

                if (node.Key.Equals("_links") && node.Value != null)
                {
                    var resource = new Dictionary <string, Link>();
                    serializer.Populate(node.Value.CreateReader(), resource);
                    response.Links = resource;
                }
            }

            return(response);
        }
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            var json = JObject.Load(reader);

            var config = new AsimovConfig();
            serializer.Populate(json.CreateReader(), config);

            var self = GetSelf(json);
            if (self != null)
                serializer.Populate(self.CreateReader(), config);
            else
                Log.ErrorFormat("Could not find agent specific config / environment for: {0}", _machineName);

            var environments = config.Environment.Split(',');

            foreach (var environment in environments)
            {
                var envConfigFile = Path.Combine(_configDir, $"config.{environment.Trim()}.json");

                if (!File.Exists(envConfigFile))
                    continue;

                Log.DebugFormat("Loading config file {0}", envConfigFile);
				PopulateFromFile(envConfigFile, serializer, config);

				var env = new DeployEnvironment();
				PopulateFromFile(envConfigFile, serializer, env);
				config.Environments.Add(env);
			}

            return config;
        }
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            List<ResolvedAction> resolvedActions = new List<ResolvedAction>();

            JArray actionsArray = JArray.Load(reader);
            foreach (JObject jobject in actionsArray)
            {
                ResolvedAction resolvedAction = new ResolvedAction();
                serializer.Populate(jobject.CreateReader(), resolvedAction);
                resolvedAction.BeaconAction = new BeaconAction();
                serializer.Populate(jobject.CreateReader(), resolvedAction.BeaconAction);
                if (jobject["content"] != null)
                {
                    serializer.Populate(jobject["content"]?.CreateReader(), resolvedAction.BeaconAction);
                    resolvedAction.BeaconAction.PayloadString = jobject["content"]["payload"]?.ToString();
                    // create json object for fallback
                    if(!string.IsNullOrEmpty(resolvedAction.BeaconAction.PayloadString))
                    {
                        resolvedAction.BeaconAction.Payload = JsonObject.Parse(resolvedAction.BeaconAction.PayloadString);
                    }
                }
                resolvedActions.Add(resolvedAction);
            }

            return resolvedActions;
        }
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            serializer.NullValueHandling = NullValueHandling.Ignore;
            if (IsMapType(objectType))
            {
                IDictionary list = new Dictionary<Object, Object>();
                serializer.Populate(reader, list);
                return list.ConvertMap(objectType);
            }
            else if (IsException(objectType))
            {
                Object exceptionObject = Activator.CreateInstance(HelpMethods.ImplementTypeDynamicly(objectType, typeof(IJavaException)));
                serializer.Populate(reader, exceptionObject);
                return exceptionObject;
            }

            Type typeWithIOpenEngSBModel;

            if (alreadyExtendedTypes.ContainsKey(objectType.Name))
            {
                typeWithIOpenEngSBModel = alreadyExtendedTypes[objectType.Name];
            }
            else
            {
                typeWithIOpenEngSBModel = HelpMethods.ImplementTypeDynamicly(objectType, typeof(IOpenEngSBModel));
                alreadyExtendedTypes.Add(objectType.Name, typeWithIOpenEngSBModel);
            }

            Object modelWithOpenEngsbModelTail = Activator.CreateInstance(typeWithIOpenEngSBModel);
            serializer.Populate(reader, modelWithOpenEngsbModelTail);
            return modelWithOpenEngsbModelTail;
        }
Пример #8
0
		public override object ReadJson (Newtonsoft.Json.JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
		{
			object instance;
			JContainer container;
			if (reader.TokenType == JsonToken.Null) {
				return null;
			}
			if (reader.TokenType == JsonToken.StartArray) {
				container = JArray.Load (reader);
				if (objectType == typeof(DynamicRow)) {
					var dynamicRow = new DynamicRow ();
					instance = dynamicRow;
					serializer.Populate (container.CreateReader (), dynamicRow.Items);
				}
				else if (objectType == typeof(DynamicItem)) {
					var dynamicTable = new DynamicTable ();
					instance = dynamicTable;
					serializer.Populate (container.CreateReader (), dynamicTable.Rows);
				}
				else throw new EtoException("Invalid object graph");
			} else {
				container = JObject.Load (reader);
				if (container["$type"] == null) {
					if (container["Rows"] != null)
						instance = new DynamicTable ();
					else if (container["Control"] != null)
						instance = new DynamicControl ();
					else
						throw new EtoException("Could not infer the type of object to create");

					serializer.Populate(container.CreateReader(), instance);
				}
				else {
					var type = Type.GetType ((string)container ["$type"]);
					if (!typeof(DynamicItem).IsAssignableFrom (type)) {
						var dynamicControl = new DynamicControl ();
						dynamicControl.Control = serializer.Deserialize (container.CreateReader ()) as Control;
						instance = dynamicControl;
					} else {
						instance = serializer.Deserialize (container.CreateReader ());
					}
				}
			}
			if (objectType == typeof(DynamicRow) && instance.GetType () != typeof(DynamicRow)) {
				var row = new DynamicRow();
				row.Items.Add (instance as DynamicItem);
				return row;
			}

			return instance;
		}
		public override object ReadJson(JsonReader reader, Type objectType, object existingValue,
										JsonSerializer serializer)
		{
			if (reader.TokenType == JsonToken.StartArray)
			{
				var list = new List<ShardsSegment>();
				serializer.Populate(reader, list);
				return list.First();
			}

			var o = new ShardsSegment();
			serializer.Populate(reader, o);
			return o;
		}
Пример #10
0
        public override object ReadJson(Newtonsoft.Json.JsonReader reader, Type objectType, object existingValue, Newtonsoft.Json.JsonSerializer serializer)
        {
            var leagueList = new List <League>();
            var games      = JObject.Load(reader);
            var count      = (int)games["count"];

            for (int x = 0; x < count; x++)
            {
                var gameDict = games[x.ToString()];
                var game     = gameDict["game"];

                if (game[0]["game_key"].ToString() == "331")
                {
                    var leagues    = game[1]["leagues"];
                    var numLeagues = (int)leagues["count"];

                    for (int y = 0; y < numLeagues; y++)
                    {
                        var leagueDict = leagues[y.ToString()];
                        var league     = leagueDict["league"][0];
                        var leagueObj  = JObject.Parse(league.ToString());
                        var target     = JsonConvert.DeserializeObject <League>(leagueObj.ToString());

                        serializer.Populate(leagueObj.CreateReader(), target);
                        leagueList.Add(target);
                    }
                }
            }

            return(new LeagueCollection {
                Leagues = leagueList
            });
        }
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, Newtonsoft.Json.JsonSerializer serializer)
        {
            object objectToDeserialize = Activator.CreateInstance(objectType);

            serializer.Populate(reader, objectToDeserialize);
            return(objectToDeserialize);
        }
Пример #12
0
        public RomSettings(string jsonBase, string jsonMerge)
        {
            JObject baseSettings;
            JObject mergeSettings;

            using (var reader = File.OpenText(jsonBase))
            {
                baseSettings = JObject.Parse(reader.ReadToEnd());
            }

            if (jsonMerge != null)
            {
                using (var reader = File.OpenText(jsonMerge))
                {
                    mergeSettings = JObject.Parse(reader.ReadToEnd());
                }

                baseSettings.Merge(mergeSettings);
            }

            using (var reader = baseSettings.CreateReader())
            {
                JsonSerializer serializer = new JsonSerializer();
                serializer.Populate(reader, this);
            }
        }
        /// <summary>
        ///     Read JSON from stream
        /// </summary>
        /// <param name="reader">JSON Reader</param>
        /// <param name="objectType">Object Type</param>
        /// <param name="existingValue">Existing Type</param>
        /// <param name="serializer">Serializer</param>
        /// <returns>Object instance</returns>
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue,
            JsonSerializer serializer)
        {
            // Validate Arguments
            if (reader == null)
                throw new ArgumentNullException(nameof(reader));
            if (objectType == null)
                throw new ArgumentNullException(nameof(objectType));
            if (serializer == null)
                throw new ArgumentNullException(nameof(serializer));
            if (serializer.ContractResolver == null)
                throw new ArgumentException(string.Format(CultureInfo.CurrentUICulture, ExceptionMessages.NoContractResolver, objectType.FullName));

            // Create an instance of the applicable type
            var contract = serializer.ContractResolver.ResolveContract(objectType);
            if (contract == null)
                throw new InvalidOperationException(string.Format(CultureInfo.CurrentUICulture, ExceptionMessages.CouldNotResolveContract, objectType.FullName));

            var creator = contract.DefaultCreator;
            if (creator == null)
                throw new InvalidOperationException(string.Format(CultureInfo.CurrentUICulture, ExceptionMessages.TypeMissingDefaultCreator, objectType.FullName));
            var instance = (AggregateBase)creator();

            serializer.Populate(reader, instance);

            // Return the type we've created
            return instance;
        }
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            var reference = SupportedTypes[objectType].Invoke();
            serializer.Populate(reader, reference);

            return reference;
        }
Пример #15
0
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, Newtonsoft.Json.JsonSerializer serializer)
        {
            var product = existingValue as Product ?? new Product();
            var jObject = JObject.Load(reader);

            serializer.Populate(jObject.CreateReader(), product);
            product.Attributes = new Dictionary <string, string>();

            foreach (var item in jObject.Children())
            {
                var jProperty = item as JProperty;
                if (jProperty != null)
                {
                    var name     = jProperty.Name;
                    var property = product.GetType().GetProperty(name);
                    if (property == null && name != "messages")
                    {
                        if (product.Attributes.ContainsKey(name))
                        {
                            product.Attributes.Remove(name);
                        }
                        string value = null;
                        if (jProperty.Value != null)
                        {
                            value = jProperty.Value.Value <string>();
                        }
                        product.Attributes.Add(name, value);
                    }
                }
            }

            product.StartTracking();
            return(product);
        }
Пример #16
0
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            if (serializer == null)
            {
                throw new ArgumentNullException(nameof(serializer));
            }

            var objectDictionary = new Dictionary<string, object>();
            serializer.Populate(reader, objectDictionary);

            var propertyDictionary = new Dictionary<string, SerializedPropertyInfo>();
            foreach (string key in objectDictionary.Keys)
            {
                Type propertyType = objectDictionary[key].GetType();

                string serializedValue = objectDictionary[key].ToString();
                bool isString = false;

                if (propertyType == typeof(bool))
                {
                    serializedValue = serializedValue.ToLowerInvariant();
                }
                else if (propertyType == typeof(string))
                {
                    serializedValue = '"' + serializedValue + '"';
                    isString = true;
                }

                propertyDictionary.Add(
                    key,
                    new SerializedPropertyInfo(serializedValue, isString));
            }

            return propertyDictionary;
        }
Пример #17
0
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, Newtonsoft.Json.JsonSerializer s)
        {
            s.NullValueHandling = NullValueHandling.Include;

            if (existingValue == null)
            {
                Type generated = this.channel.FindType(objectType);

                return(s.Deserialize(reader, generated));
            }
            else
            {
                if (reader.TokenType == JsonToken.Null)
                {
                    reader.Skip();
                    return(null);
                }
                else
                {
                    s.Populate(reader, existingValue);

                    return(existingValue);
                }
            }
        }
Пример #18
0
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue,
										JsonSerializer serializer)
        {
            // {"indexname":{"warmers":{"warmername": {...}}}}
            var dict = new Dictionary<string, Dictionary<string, Dictionary<string, WarmerMapping>>>();
            serializer.Populate(reader, dict);

            Dictionary<string, Dictionary<string, WarmerMapping>> indices = new Dictionary<string, Dictionary<string, WarmerMapping>>();
            foreach (var kv in dict)
            {
                var indexDict = kv.Value;
                Dictionary<string, WarmerMapping> warmers;
                if (!indexDict.TryGetValue("warmers", out warmers) || warmers == null)
                    continue;
                foreach (var kvW in warmers)
                {
                    kvW.Value.Name = kvW.Key;
                }
                indices.Add(kv.Key, warmers);
            }

            return new WarmerResponse
            {
                Indices = indices
            };
        }
        public override object ReadJson(
            JsonReader reader,
            Type objectType,
            object existingValue,
            Newtonsoft.Json.JsonSerializer serializer)
        {
            Type genericTypeDefinition = objectType.GetGenericTypeDefinition();
            Type genericArgument       = objectType.GetGenericArguments()[0];
            Type constructed           = genericTypeDefinition.MakeGenericType(genericArgument);

            var wrapper = Activator.CreateInstance(constructed);

            Type       instanceType = typeof(List <>).MakeGenericType(genericArgument);
            var        targetItems  = Activator.CreateInstance(instanceType);
            JContainer jObject      = JArray.Load(reader);

            if (targetItems != null)
            {
                serializer.Populate(jObject.CreateReader(), targetItems);
            }

            CheckAndSetItemsList(genericArgument, wrapper, targetItems);

            return(wrapper);
        }
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            object retVal = null;
            var obj = JObject.Load(reader);
            if (objectType == typeof(Member))
            {
                var pt = obj["memberType"];
                if (pt == null)
                {
                    throw new ArgumentException("Missing memberType", "memberType");
                }

                string memberType = pt.Value<string>();
                retVal = _membersFactory.TryCreateMember(memberType);
                if (retVal == null)
                {
                    throw new NotSupportedException("Unknown memberType: " + memberType);
                }

            }
            else if(objectType == typeof(MembersSearchCriteria))
            {
                retVal = _membersFactory.CreateMemberSearchCriteria();
            }
            serializer.Populate(obj.CreateReader(), retVal);
            return retVal;
        }
        /// <summary>
        /// Reads the JSON representation of the object.
        /// </summary>
        /// <param name="reader">The <see cref="T:Newtonsoft.Json.JsonReader" /> to read from.</param>
        /// <param name="objectType">Type of the object.</param>
        /// <param name="existingValue">The existing value of object being read.</param>
        /// <param name="serializer">The calling serializer.</param>
        /// <returns>
        /// The object value.
        /// </returns>
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            JObject jobject = JObject.Load(reader);
            object target = null;

            if (jobject != null)
            {
                var keyType = jobject["key_type"].Value<string>();

                if (string.Equals(keyType, SSHKeyType.otp.ToString(), StringComparison.OrdinalIgnoreCase))
                {
                    target = new SSHOTPRoleDefinition();
                }
                else
                {
                    if (string.Equals(keyType, SSHKeyType.dynamic.ToString(), StringComparison.OrdinalIgnoreCase))
                    {
                        target = new SSHDynamicRoleDefinition();
                    }
                }
            }

            if (target != null)
            {
                serializer.Populate(jobject.CreateReader(), target);
            }

            return target;
        }
Пример #22
0
		public override object ReadJson(Newtonsoft.Json.JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
		{
			if (reader.ValueType == null)
			{
				var obj = JObject.Load(reader);
				Type type = null;
				var typeToken = obj["$type"];
				if (typeToken != null)
				{
					string assemblyName = null;
					var typeName = typeToken.Value<string>();
					var assemblyIndex = typeName.IndexOf(',');
					if (assemblyIndex > 0)
					{
						assemblyName = typeName.Substring(assemblyIndex + 1).Trim();
						typeName = typeName.Substring(0, assemblyIndex);
					}
					type = serializer.Binder.BindToType(assemblyName, typeName);
				}
				else
					type = objectType;

				var target = Activator.CreateInstance(type);
				serializer.Populate(obj.CreateReader(), target);
				return target;
			}
			if (objectType == reader.ValueType)
				return reader.Value;
			var converter = GetConverter(objectType, reader.ValueType);
			if (converter != null)
			{
				return converter.ConvertFrom(reader.Value);
			}
			return reader.Value;
		}
 public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
 {
     var mobileServiceFile = new MobileServiceFile();
     serializer.Populate(reader, mobileServiceFile);
     
     return mobileServiceFile;
 }
        /// <inheritdoc />
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            var jsonObject = JObject.Load(reader);
            var sourceKeys = GetKeys(jsonObject).Select(k => k.Key).ToList();

            var childTypes = this.GetChildTypes(objectType);

            var testObjects = childTypes.Select(Activator.CreateInstance)
                .Select(instance => new { Instance = instance, SerializedInstance = Serialize(serializer, instance) })
                .ToList();

            var testKeys = testObjects.ToDictionary(
                to => to,
                to => GetKeys(to.SerializedInstance).Select(kvp => kvp.Key).ToList());

            var target = testObjects.Select(to => new { TestObject = to, Keys = testKeys[to] })
                .OrderBy(t => t.Keys.Count)
                .FirstOrDefault(t => !sourceKeys.Except(t.Keys).Any()); // Any keys in source that are not in the target object?

            if (target == null)
            {
                throw new JsonSerializationException(
                    string.Format(CultureInfo.InvariantCulture, "Unable to deserialize to type {0}, value: {1}", objectType, jsonObject));
            }

            serializer.Populate(jsonObject.CreateReader(), target.TestObject.Instance);

            return target.TestObject.Instance;
        }
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            var jObject = JObject.Load(reader);

            object target;
            if (jObject.Property("module") != null)
            {
                target = new ModuleViewDefinition();
            }
            else if (jObject.Property("template") != null)
            {
                var template = _templateRespository.GetTemplateAsync(jObject.Property("template").Value.Value<string>()).Result;
                var type = _typeProvider.GetModelTypeFromTemplateAsync(template).Result;
                target = Activator.CreateInstance(typeof(PageViewDefinition<>).MakeGenericType(type), template);
                
            }
            else
                return serializer.Deserialize(jObject.CreateReader(), objectType);

            var jObjectReader = jObject.CreateReader();
            jObjectReader.Culture = reader.Culture;
            jObjectReader.DateParseHandling = reader.DateParseHandling;
            jObjectReader.DateTimeZoneHandling = reader.DateTimeZoneHandling;
            jObjectReader.FloatParseHandling = reader.FloatParseHandling;

            serializer.Populate(jObjectReader, target);

            return target;
        }
Пример #26
0
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            var obj = JObject.Load(reader);
            ProfitSharingStrategy strategy;

            var method = obj["Method"];
            if (method == null)
            {
                throw new ArgumentNullException("Type", "Order type is null");
            }

            var profitSharingMethod = (ProfitSharingMethod)Enum.Parse(typeof(ProfitSharingMethod), method.Value<string>());
            switch (profitSharingMethod)
            {
                case ProfitSharingMethod.FLAT_RATE:
                    strategy = new FlatRateStrategy();
                    break;
                case ProfitSharingMethod.PRICE_PERCENTAGE:
                    strategy = new PricePercentageStrategy();
                    break;
                default:
                    throw new NotImplementedException($"{profitSharingMethod.ToString()} is invalid/not supported");
            }

            serializer.Populate(obj.CreateReader(), strategy);
            return strategy;
        }
Пример #27
0
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            if (reader.TokenType == JsonToken.Null)
                return null;

            var keyType = objectType.GetGenericArguments()[0];
            var keyValueType = keyType.BaseType.GetGenericArguments()[0];
            var valueType = objectType.GetGenericArguments()[1];
            var intermediateDictionaryType = typeof(Dictionary<,>).MakeGenericType(typeof(string), valueType);
            var intermediateDictionary = (IDictionary)Activator.CreateInstance(intermediateDictionaryType);
            serializer.Populate(reader, intermediateDictionary);

            var valueProperty = keyType.GetProperty("Value");
            var finalDictionary = (IDictionary)Activator.CreateInstance(objectType);
            foreach (DictionaryEntry pair in intermediateDictionary)
            {
                object value;
                if (keyValueType == typeof(Guid))
                    value = Guid.Parse(pair.Key.ToString());
                else
                    value = Convert.ChangeType(pair.Key, keyValueType, null);

                var key = Activator.CreateInstance(keyType);
                valueProperty.SetValue(key, value, null);
                finalDictionary.Add(key, pair.Value);
            }
            return finalDictionary;
        }
        /// <summary>
        /// Deserializes JSON into an array of IFormHandler.
        /// </summary>
        /// <returns>
        /// An array of IFormHandler.
        /// </returns>
        public override object ReadJson(JsonReader reader,
            Type objectType, object existingValue,
            JsonSerializer serializer)
        {
            // Variables.
            var handlers = new List<IFormHandler>();
            var jsonArray = JArray.Load(reader);

            // Deserialize each form handler.
            foreach (var item in jsonArray)
            {

                // Create a form handler instance by the handler type ID.
                var jsonObject = item as JObject;
                var strTypeId = jsonObject["TypeId"].Value<string>();
                var typeId = Guid.Parse(strTypeId);
                var instance = InstantiateHandlerByTypeId(typeId);

                // Populate the form handler instance.
                serializer.Populate(jsonObject.CreateReader(), instance);
                handlers.Add(instance);

            }

            // Return array of form handlers.
            return handlers.ToArray();
        }
Пример #29
0
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, Newtonsoft.Json.JsonSerializer serializer)
        {
            var Order = existingValue as Order ?? new Order();

            //var jObject = JObject.Load(reader);

            serializer.Populate(reader, Order);

            /*Order.Attributes = new Dictionary<string, string>();
             *
             * foreach (var item in jObject.Children())
             * {
             *  var jProperty = item as JProperty;
             *  if (jProperty != null)
             *  {
             *      var name = jProperty.Name;
             *      var property = Order.GetType().GetProperty(name);
             *      if (property == null && name != "messages")
             *      {
             *          if (Order.Attributes.ContainsKey(name)) Order.Attributes.Remove(name);
             *          string value = null;
             *          if (jProperty.Value != null) value = jProperty.Value.Value<string>();
             *          Order.Attributes.Add(name, value);
             *      }
             *  }
             * }*/

            Order.StartTracking();
            return(Order);
        }
Пример #30
0
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            var obj = JObject.Load(reader);
            var type = obj["type"];

            if (type == null)
            {
                throw new ArgumentNullException("type", "GeoJson object type is provided null");
            }

            IGeoJsonModel baseGeoJson;
            string geoJsonType = type.Value<string>();
            switch (geoJsonType)
            {
                case "LineString":
                    baseGeoJson = new LineString();
                    break;
                case "Point":
                    baseGeoJson = new Point();
                    break;
                case "Polygon":
                    baseGeoJson = new Polygon();
                    break;
                default:
                    throw new NotSupportedException("GeoJson Entry type invalid/no supported - " + geoJsonType);
            }

            serializer.Populate(obj.CreateReader(), baseGeoJson);
            return baseGeoJson;

        }
Пример #31
0
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            var obj = JObject.Load(reader);
            OrderModel orderModel;

            var type = obj["Type"];
            if (type == null)
            {
                throw new ArgumentNullException("Type", "Order type is null");
            }

            string orderType = type.Value<string>();
            switch (orderType)
            {
                case OrderTypes.Ride:
                    orderModel = new RideOrder();
                    break;
                case OrderTypes.Delivery:
                    orderModel = new DeliveryOrder();
                    break;
                case OrderTypes.ClassifiedDelivery:
                    orderModel = new ClassifiedDeliveryOrder();
                    break;
                default:
                    throw new NotSupportedException(string.Concat("Order Entry type invalid/not supported - ", orderType));
            }

            serializer.Populate(obj.CreateReader(), orderModel);
            return orderModel;

        }
        /// <summary>
        /// Reads the JSON representation of the object.
        /// </summary>
        /// <param name="reader">The <see cref="T:Newtonsoft.Json.JsonReader" /> to read from.</param>
        /// <param name="objectType">Type of the object.</param>
        /// <param name="existingValue">The existing value of object being read.</param>
        /// <param name="serializer">The calling serializer.</param>
        /// <returns>
        /// The object value.
        /// </returns>
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            JObject jobject = JObject.Load(reader);
            object target = null;

            if (jobject != null)
            {
                var typeValue = jobject["type"].Value<string>();
                var type = new AuditBackendType(typeValue);

                if (type == AuditBackendType.File)
                {
                    target = new FileAuditBackend();
                }
                else
                {
                    if (type == AuditBackendType.Syslog)
                    {
                        target = new SyslogAuditBackend();
                    }
                }

                if (target == null)
                {
                    target = new CustomAuditBackend(new AuditBackendType(typeValue));
                }

                serializer.Populate(jobject.CreateReader(), target);
            }

            return target;
        }
Пример #33
0
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            var obj = JObject.Load(reader);
            RegistrationModelBase model;

            var type = obj["Type"];
            if (type == null)
            {
                obj["Type"] = ((IdentityTypes)0).ToString();
                type = obj["Type"];
            }

            string modelType = type.Value<string>();
            IdentityTypes actualType;
            if (!Enum.TryParse<IdentityTypes>(modelType, out actualType))
                throw new NotSupportedException("Invalid AssetType Provided");

            switch (actualType)
            {
                case IdentityTypes.USER:
                    model = new UserRegistrationModel();
                    break;
                case IdentityTypes.ENTERPRISE:
                    model = new EnterpriseUserRegistrationModel();
                    break;
                default:
                    model = new AssetRegistrationModel();
                    break;
            }

            serializer.Populate(obj.CreateReader(), model);
            return model;
        }
 public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
 {
     JObject jObject = JObject.Load(reader);
     object registration = jObject.Property("templateBody") == null ? new Registration() : new TemplateRegistration();
     serializer.Populate(jObject.CreateReader(), registration);
     return registration;
 }
Пример #35
0
		public override object ReadJson(Newtonsoft.Json.JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
		{
			object instance;
			JContainer container;
			if (reader.TokenType == JsonToken.Null)
			{
				return null;
			}
			container = JObject.Load(reader);
			if (container["$type"] == null)
			{
				instance = new StackLayoutItem();
				serializer.Populate(container.CreateReader(), instance);
			}
			else
			{
				var type = Type.GetType((string)container["$type"]);
				if (!typeof(StackLayoutItem).IsAssignableFrom(type))
				{
					var item = new StackLayoutItem();
					item.Control = serializer.Deserialize(container.CreateReader()) as Control;
					instance = item;
				}
				else
				{
					instance = serializer.Deserialize(container.CreateReader());
				}
			}
			return instance;
		}
        /// <summary>
        ///   Creates a new object via the Factory.  Loads the instance via the serializer.
        /// </summary>
        /// <param name="reader">The JsonReader</param>
        /// <param name="objectType">The Type of DTO</param>
        /// <param name="existingValue">The DTO</param>
        /// <param name="serializer">JsonSerializer</param>
        /// <returns></returns>
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            JsonReader objectReader = null;
            
            var instance = _container.CreateInstance(objectType);
            if (reader.TokenType == JsonToken.StartObject || reader.TokenType == JsonToken.StartArray)
            {
                if (reader.TokenType == JsonToken.StartObject)
                {
                    var jObject = JObject.Load(reader);
                    objectReader = jObject.CreateReader();
                }

                if (reader.TokenType == JsonToken.StartArray)
                {
                    var jArray = JArray.Load(reader);
                    objectReader = jArray.CreateReader();
                }
                
                if(objectReader != null)
                    serializer.Populate(objectReader, instance);
            }

            return instance;
        }
		public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
		{
			if (reader.TokenType == JsonToken.Null) return null;

			var filter =  new SourceFilter();
			switch (reader.TokenType)
			{
				case JsonToken.Boolean:
					filter.Exclude = new[] { "*" };
					break;
				case JsonToken.String:
					filter.Include = new [] { (string)reader.Value };
					break;
				case JsonToken.StartArray:
					var include = new List<string>();
					while (reader.Read() && reader.TokenType != JsonToken.EndArray)
						include.Add((string)reader.Value);
					filter.Include = include.ToArray();
					break;
				default:
					serializer.Populate(reader, filter);
					break;
			}

			return filter;
		}
Пример #38
0
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, Newtonsoft.Json.JsonSerializer serializer)
        {
            JObject   jObject   = JObject.Load(reader);
            Parameter parameter = new Parameter();

            serializer.Populate(jObject.CreateReader(), parameter);
            return(parameter);
        }
Пример #39
0
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, Newtonsoft.Json.JsonSerializer serializer)
        {
            JObject jObject = JObject.Load(reader);
            Query   query   = new Query();

            serializer.Populate(jObject.CreateReader(), query);
            return(query);
        }
Пример #40
0
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, Newtonsoft.Json.JsonSerializer serializer)
        {
            JObject jObject = JObject.Load(reader);
            T       target  = Create(objectType, jObject);

            serializer.Populate(jObject.CreateReader(), target);
            return(target);
        }
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, Newtonsoft.Json.JsonSerializer serializer)
        {
            var customer = existingValue as Customer ?? new Customer();

            serializer.Populate(reader, customer);

            customer.StartTracking();
            return(customer);
        }
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, Newtonsoft.Json.JsonSerializer serializer)
        {
            var imageInfo = existingValue as ImageInfo ?? new ImageInfo();
            var jObject   = JObject.Load(reader);

            serializer.Populate(jObject.CreateReader(), imageInfo);
            imageInfo.StartTracking();
            return(imageInfo);
        }
Пример #43
0
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, Newtonsoft.Json.JsonSerializer serializer)
        {
            var option = existingValue as CustomOption ?? new CustomOption();

            serializer.Populate(reader, option);

            option.StartTracking();
            return(option);
        }
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, Newtonsoft.Json.JsonSerializer serializer)
        {
            var price = existingValue as GroupPrice ?? new GroupPrice();

            serializer.Populate(reader, price);
            price.StartTracking();

            return(price);
        }
Пример #45
0
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, Newtonsoft.Json.JsonSerializer serializer)
        {
            var OrderAddress = existingValue as OrderAddress ?? new OrderAddress();

            serializer.Populate(reader, OrderAddress);

            OrderAddress.StartTracking();
            return(OrderAddress);
        }
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, Newtonsoft.Json.JsonSerializer serializer)
        {
            var stockItem = existingValue as StockItem ?? new StockItem();

            serializer.Populate(reader, stockItem);

            stockItem.StartTracking();
            return(stockItem);
        }
Пример #47
0
        public override object ReadJson(Newtonsoft.Json.JsonReader reader, Type objectType, object existingValue, Newtonsoft.Json.JsonSerializer serializer)
        {
            var jObject    = JObject.ReadFrom(reader);
            var pocketItem = new PocketItem();

            serializer.Populate(jObject.CreateReader(), pocketItem);
            pocketItem.Json = jObject.ToString();

            return(pocketItem);
        }
 public override object ReadJson(JsonReader reader, Type objectType, object existingValue, Newtonsoft.Json.JsonSerializer serializer)
 {
     if (reader.TokenType == JsonToken.StartObject)
     {
         ObjectValue objectValue = new ObjectValue();
         serializer.Populate(reader, objectValue);
         return(objectValue);
     }
     return(null);
 }
Пример #49
0
 public void Populate(JToken data, object obj)
 {
     if (_jsonSerializer == null)
     {
         _jsonSerializer = Newtonsoft.Json.JsonSerializer.CreateDefault(_settings);
     }
     using (var sr = data.CreateReader())
     {
         _jsonSerializer.Populate(sr, obj);
     }
 }
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, Newtonsoft.Json.JsonSerializer serializer)
        {
            serializer.NullValueHandling    = NullValueHandling.Ignore;
            serializer.DefaultValueHandling = DefaultValueHandling.Populate;
            var jsonObject = JObject.Load(reader);

            var target = Create(objectType, jsonObject);

            serializer.Populate(jsonObject.CreateReader(), target);

            return(target);
        }
        /// <summary>Reads the JSON representation of the object.</summary>
        /// <param name="reader">The <see cref="T:Newtonsoft.Json.JsonReader" /> to read from.</param>
        /// <param name="objectType">Type of the object.</param>
        /// <param name="existingValue">The existing value of object being read.</param>
        /// <param name="serializer">The calling serializer.</param>
        /// <returns>The object value.</returns>
        public override object ReadJson(JsonReader reader, Type objectType,
                                        object existingValue, Newtonsoft.Json.JsonSerializer serializer)
        {
            var jsonObject = JObject.Load(reader);
            var target     = Create(objectType, jsonObject, serializer);

            if (target != null)
            {
                serializer.Populate(jsonObject.CreateReader(), target);
            }
            return(target);
        }
Пример #52
0
 public static T ToObject <T> (this string str, object inObject)
 {
     if (inObject is T && inObject != null)
     {
         var serializer = new Newtonsoft.Json.JsonSerializer();
         using (var reader = new StringReader(str)) {
             var outObj = (T)inObject;
             serializer.Populate(reader, outObj);
             return(outObj);
         }
     }
     return(str.ToObject <T> ());
 }
Пример #53
0
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, Newtonsoft.Json.JsonSerializer serializer)
        {
            // Load JObject from stream
            var jObject = JObject.Load(reader);

            // Create target object based on JObject
            var target = Create(objectType, jObject);

            // Populate the object properties
            serializer.Populate(jObject.CreateReader(), target);

            return(target);
        }
 public override object ReadJson(JsonReader reader, Type objectType, object existingValue, Newtonsoft.Json.JsonSerializer serializer)
 {
     if (reader.TokenType == JsonToken.StartObject)
     {
         Error error = (Error)Activator.CreateInstance(objectType);
         while (reader.Read())
         {
             if (reader.TokenType == JsonToken.PropertyName)
             {
                 if (reader.Value.Equals("errorCode"))
                 {
                     error.ErrorCode = reader.ReadAsInt32();
                 }
                 else if (reader.Value.Equals("message"))
                 {
                     error.Message = reader.ReadAsString();
                 }
                 else if (reader.Value.Equals("refId"))
                 {
                     error.RefId = reader.ReadAsString();
                 }
                 else if (reader.Value.Equals("detail"))
                 {
                     reader.Read();
                     if (reader.TokenType == JsonToken.StartObject)
                     {
                         ErrorDetail errorDetail = new ErrorDetail();
                         serializer.Populate(reader, errorDetail);
                         error.Detail = errorDetail;
                         reader.Read(); // JsonToken.EndObject
                     }
                     else if (reader.TokenType == JsonToken.StartArray)
                     {
                         IList <ErrorDetail> errorDetails = null;
                         errorDetails = serializer.Deserialize <IList <ErrorDetail> >(reader);
                         error.Detail = errorDetails;
                         reader.Read(); // JsonToken.EndArray
                     }
                 }
             }
             else if (reader.TokenType == JsonToken.EndObject)
             {
                 break;
             }
         }
         return(error);
     }
     return(null);
 }
Пример #55
0
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, Newtonsoft.Json.JsonSerializer serializer)
        {
            JObject jObject = JObject.Load(reader);
            DatabaseOperationType dbOperationType = (DatabaseOperationType)((int)jObject["OpT"]);

            switch (dbOperationType)
            {
            case DatabaseOperationType.WriteQuery:
                WriteQueryOperation writeQueryOperation = new WriteQueryOperation();
                serializer.Populate(jObject.CreateReader(), writeQueryOperation);
                return(writeQueryOperation);

            default:
                return(serializer.Deserialize(reader));
            }
        }
        public override object ReadJson(
            JsonReader reader,
            Type objectType,
            object existingValue,
            Newtonsoft.Json.JsonSerializer serializer)
        {
            JObject jObject = JObject.Load(reader);
            var     target  = RetrieveScheduleResponseType(jObject);

            if (target != null)
            {
                serializer.Populate(jObject.CreateReader(), target);
            }

            return(target);
        }
Пример #57
0
        /// <summary>
        /// Populates the object with values from the JSON string using <see cref="JsonSerializerSettings"/>.
        /// </summary>
        /// <param name="value">The JSON to populate values from.</param>
        /// <param name="target">The target object to populate values onto.</param>
        /// <param name="settings">
        /// The <see cref="JsonSerializerSettings"/> used to deserialize the object.
        /// If this is <c>null</c>, default serialization settings will be used.
        /// </param>
        public static void PopulateObject(string value, object target, JsonSerializerSettings settings)
        {
            JsonSerializer jsonSerializer = JsonSerializer.CreateDefault(settings);

            using (JsonReader jsonReader = new JsonTextReader(new StringReader(value)))
            {
                jsonSerializer.Populate(jsonReader, target);

                if (settings != null && settings.CheckAdditionalContent)
                {
                    while (jsonReader.Read())
                    {
                        if (jsonReader.TokenType != JsonToken.Comment)
                        {
                            throw JsonSerializationException.Create(jsonReader, "Additional text found in JSON string after finishing deserializing object.");
                        }
                    }
                }
            }
        }
        /// <summary>Populates the object with values from the JSON string using <see cref="JsonSerializer"/>.</summary>
        /// <param name="jsonSerializer">The <see cref="JsonSerializer"/> used to deserialize the object.</param>
        /// <param name="value">The JSON to populate values from.</param>
        /// <param name="offset"></param>
        /// <param name="count"></param>
        /// <param name="target">The target object to populate values onto.</param>
        public static void PopulateObject(this JsonSerializer jsonSerializer, object target, byte[] value, int offset, int count)
        {
            using (var jsonReader = new JsonTextReader(new StreamReaderX(new MemoryStream(value, offset, count), Encoding.UTF8)))
            {
                jsonReader.ArrayPool  = JsonConvertX.GlobalCharacterArrayPool;
                jsonReader.CloseInput = false;

                jsonSerializer.Populate(jsonReader, target);

                if (jsonSerializer.CheckAdditionalContent)
                {
                    while (jsonReader.Read())
                    {
                        if (jsonReader.TokenType != JsonToken.Comment)
                        {
                            ThrowJsonSerializationException(jsonReader);
                        }
                    }
                }
            }
        }
        /// <summary>Populates the object with values from the JSON string using <see cref="JsonSerializer"/>.</summary>
        /// <param name="jsonSerializer">The <see cref="JsonSerializer"/> used to deserialize the object.</param>
        /// <param name="value">The JSON to populate values from.</param>
        /// <param name="target">The target object to populate values onto.</param>
        public static void PopulateObject(this JsonSerializer jsonSerializer, object target, string value)
        {
            using (var jsonReader = new JsonTextReader(new StringReader(value)))
            {
                jsonReader.ArrayPool  = JsonConvertX.GlobalCharacterArrayPool;
                jsonReader.CloseInput = false;

                jsonSerializer.Populate(jsonReader, target);

                if (jsonSerializer.CheckAdditionalContent)
                {
                    while (jsonReader.Read())
                    {
                        if (jsonReader.TokenType != JsonToken.Comment)
                        {
                            ThrowJsonSerializationException(jsonReader);
                        }
                    }
                }
            }
        }
Пример #60
0
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            if (reader.TokenType == JsonToken.Null)
            {
                return(null);
            }

            var valueType = objectType.GetGenericArguments()[1];
            var intermediateDictionaryType = typeof(Dictionary <,>).MakeGenericType(typeof(string), valueType);
            var intermediateDictionary     = (IDictionary)Activator.CreateInstance(intermediateDictionaryType);

            serializer.Populate(reader, intermediateDictionary);

            var dict = (IDictionary)Activator.CreateInstance(objectType);

            foreach (DictionaryEntry pair in intermediateDictionary)
            {
                dict.Add(Enum.Parse(typeof(T), pair.Key.ToString()), pair.Value);
            }

            return(dict);
        }