Deserialize() public method

Deserializes the Json structure contained by the specified JsonReader.
public Deserialize ( JsonReader reader ) : object
reader JsonReader The that contains the JSON structure to deserialize.
return object
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            JToken value = null;
            var response = new FindConnectedObjectsResponse();
            // status
            var json = JObject.ReadFrom(reader) as JObject;
            json.TryGetValue("status", out value);
            response.Status = serializer.Deserialize<Status>(value.CreateReader());
            if (response.Status.IsSuccessful == false)
                return response;
            json.Remove("status");

            // paging info
            // Extract paging info
            json.TryGetValue("paginginfo", out value);
            response.PagingInfo = serializer.Deserialize<PagingInfo>(value.CreateReader());
            json.Remove("paginginfo");

            // extract parent label
            json.TryGetValue("parent", out value);
            var parentLabel = value.ToString();

            // Extract graph node.
            json.TryGetValue("nodes", out value);
            if (value.Type != JTokenType.Null)
            {
                var nodes = value.Values<JObject>();
                ParseNodes(response, parentLabel, nodes, serializer);
            }
            else
                response.Nodes = new List<GraphNode>();
            return response;
        }
		private IElasticCoreType GetTypeFromJObject(JObject po, JsonSerializer serializer)
		{
			JToken typeToken;
			serializer.TypeNameHandling = TypeNameHandling.None;
			if (po.TryGetValue("type", out typeToken))
			{
				var type = typeToken.Value<string>().ToLowerInvariant();
				switch (type)
				{
					case "string":
						return serializer.Deserialize(po.CreateReader(), typeof(StringMapping)) as StringMapping;
					case "float":
					case "double":
					case "byte":
					case "short":
					case "integer":
					case "long":
						return serializer.Deserialize(po.CreateReader(), typeof(NumberMapping)) as NumberMapping;
					case "date":
						return serializer.Deserialize(po.CreateReader(), typeof(DateMapping)) as DateMapping;
					case "boolean":
						return serializer.Deserialize(po.CreateReader(), typeof(BooleanMapping)) as BooleanMapping;
					case "binary":
						return serializer.Deserialize(po.CreateReader(), typeof(BinaryMapping)) as BinaryMapping;
				}
			}
			return null;
		}
Ejemplo n.º 3
0
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            IEnumerable<Dictionary<string, object>> queries = null;
            if (reader.TokenType == JsonToken.StartArray)
            {
                queries = serializer.Deserialize<IEnumerable<Dictionary<string, object>>>(reader);
            }
            else
            {
                queries = new List<Dictionary<string, object>>()
                {
                    serializer.Deserialize<Dictionary<string, object>>(reader)
                };
            }

            List<RescoreQuery> rescoreQueries = new List<RescoreQuery>();
            foreach (Dictionary<string, object> rescoreDict in queries)
            {
                Dictionary<string, object> queryDict = JsonConvert.DeserializeObject<Dictionary<string, object>>(rescoreDict.GetString(_QUERY));
                RescoreQuery rescoreQuery = new RescoreQuery(JsonConvert.DeserializeObject<IQuery>(queryDict.GetString(_RESCORE_QUERY)));

                rescoreQuery.QueryWeight = queryDict.GetDouble(_QUERY_WEIGHT, _QUERY_WEIGHT_DEFAULT);
                rescoreQuery.RescoreQueryWeight = queryDict.GetDouble(_RESCORE_QUERY_WEIGHT, _RESCORE_QUERY_WEIGHT_DEFAULT);
                rescoreQuery.ScoreMode = ScoreModeEnum.Find(queryDict.GetString(_SCORE_MODE, _SCORE_MODE_DEFAULT.ToString()));
                rescoreQuery.WindowSize = rescoreDict.GetInt32OrNull(_WINDOW_SIZE);

                rescoreQueries.Add(rescoreQuery);
            }

            return new Rescore(rescoreQueries);
        }
Ejemplo n.º 4
0
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            var relations = new Relations();
            
            var jToken = JToken.ReadFrom(reader);
            foreach (JProperty jProperty in jToken.Where(_ => _.GetType() == typeof(JProperty)).Cast<JProperty>())
            {
                if (jProperty.Value.GetType() == typeof (JArray))
                {
                    var links = serializer.Deserialize<Link[]>(jProperty.Value.CreateReader());
                    foreach (var link in links)
                    {
                        relations.Add(link);
                        link.Rel = jProperty.Name;
                    }
                }
                else
                {
                    var link = serializer.Deserialize<Link>(jProperty.Value.CreateReader());
                    link.Rel = jProperty.Name;
                    relations.Add(link);
                }
            }

            return relations;
        }
        /// <summary>
        /// Reads the JSON representation of an <see cref="EventVersion"/> instance.
        /// </summary>
        /// <param name="reader">The <see cref="JsonReader"/> to read from.</param>
        /// <param name="objectType">The type of object.</param>
        /// <param name="existingValue">The existing value of the object being read.</param>
        /// <param name="serializer">The calling serializer.</param>
        public override Object ReadJson(JsonReader reader, Type objectType, Object existingValue, JsonSerializer serializer)
        {
            if (!reader.CanReadObject())
                return null;

            var item = 0;
            var count = 0;
            var version = 0;
            while (reader.Read() && reader.TokenType != JsonToken.EndObject)
            {
                String propertyName;
                if (!reader.TryGetProperty(out propertyName))
                    continue;

                switch (propertyName)
                {
                    case "v":
                        version = serializer.Deserialize<Int32>(reader);
                        break;
                    case "c":
                        count = serializer.Deserialize<Int32>(reader);
                        break;
                    case "i":
                        item = serializer.Deserialize<Int32>(reader);
                        break;
                }
            }

            return new EventVersion(version, count, item);
        }
        public static void Init(string baseFolder)
        {
            BaseFolder = baseFolder;

            //InitData();
            var serializer = new JsonSerializer();
            using (StreamReader file = File.OpenText(Path.Combine(BaseFolder, StatusesFilename)))
            {
                foreach (
                    var twitterStatus in
                        (List<TwitterStatus>) serializer.Deserialize(file, typeof (List<TwitterStatus>)))
                {
                    _statuses.TryAdd(twitterStatus.Id, twitterStatus);
                }
            }

            using (StreamReader file = File.OpenText(Path.Combine(BaseFolder, ResourcesFilename)))
            {
                foreach (
                    var stringResource in
                        (List<StringResource>)serializer.Deserialize(file, typeof(List<StringResource>)))
                {
                    _resources.TryAdd(stringResource.Key, stringResource);
                }
            }
        }
		public override void Copy(ODataObject source, JsonSerializer serializer)
		{
			if(source == null || serializer == null) return;
			base.Copy(source, serializer);

			var typedSource = source as AdvancedSearchResults;
			if(typedSource != null)
			{
				PartialResults = typedSource.PartialResults;
				Results = typedSource.Results;
				TimedOut = typedSource.TimedOut;
			}
			else
			{
				JToken token;
				if(source.TryGetProperty("PartialResults", out token) && token.Type != JTokenType.Null)
				{
					PartialResults = (bool)serializer.Deserialize(token.CreateReader(), typeof(bool));
				}
				if(source.TryGetProperty("Results", out token) && token.Type != JTokenType.Null)
				{
					Results = (IEnumerable<SearchResult>)serializer.Deserialize(token.CreateReader(), typeof(IEnumerable<SearchResult>));
				}
				if(source.TryGetProperty("TimedOut", out token) && token.Type != JTokenType.Null)
				{
					TimedOut = (bool)serializer.Deserialize(token.CreateReader(), typeof(bool));
				}
			}
		}
Ejemplo n.º 8
0
		public override void Copy(ODataObject source, JsonSerializer serializer)
		{
			if(source == null || serializer == null) return;
			base.Copy(source, serializer);

			var typedSource = source as Principal;
			if(typedSource != null)
			{
				Name = typedSource.Name;
				Email = typedSource.Email;
				Username = typedSource.Username;
				Domain = typedSource.Domain;
			}
			else
			{
				JToken token;
				if(source.TryGetProperty("Name", out token) && token.Type != JTokenType.Null)
				{
					Name = (string)serializer.Deserialize(token.CreateReader(), typeof(string));
				}
				if(source.TryGetProperty("Email", out token) && token.Type != JTokenType.Null)
				{
					Email = (string)serializer.Deserialize(token.CreateReader(), typeof(string));
				}
				if(source.TryGetProperty("Username", out token) && token.Type != JTokenType.Null)
				{
					Username = (string)serializer.Deserialize(token.CreateReader(), typeof(string));
				}
				if(source.TryGetProperty("Domain", out token) && token.Type != JTokenType.Null)
				{
					Domain = (string)serializer.Deserialize(token.CreateReader(), typeof(string));
				}
			}
		}
        public override void Copy(ODataObject source, JsonSerializer serializer)
        {
            if(source == null || serializer == null) return;
            base.Copy(source, serializer);

            var typedSource = source as DownloadSpecification;
            if(typedSource != null)
            {
                DownloadToken = typedSource.DownloadToken;
                PrepareXmlInfo = typedSource.PrepareXmlInfo;
                DownloadUrl = typedSource.DownloadUrl;
                DownloadPrepStartURL = typedSource.DownloadPrepStartURL;
            }
            else
            {
                JToken token;
                if(source.TryGetProperty("DownloadToken", out token) && token.Type != JTokenType.Null)
                {
                    DownloadToken = (string)serializer.Deserialize(token.CreateReader(), typeof(string));
                }
                if(source.TryGetProperty("PrepareXmlInfo", out token) && token.Type != JTokenType.Null)
                {
                    PrepareXmlInfo = (string)serializer.Deserialize(token.CreateReader(), typeof(string));
                }
                if(source.TryGetProperty("DownloadUrl", out token) && token.Type != JTokenType.Null)
                {
                    DownloadUrl = (Uri)serializer.Deserialize(token.CreateReader(), typeof(Uri));
                }
                if(source.TryGetProperty("DownloadPrepStartURL", out token) && token.Type != JTokenType.Null)
                {
                    DownloadPrepStartURL = (Uri)serializer.Deserialize(token.CreateReader(), typeof(Uri));
                }
            }
        }
        /// <summary>
        /// Reads the JSON representation of a <see cref="CommandEnvelope"/> instance.
        /// </summary>
        /// <param name="reader">The <see cref="JsonReader"/> to read from.</param>
        /// <param name="objectType">The type of object.</param>
        /// <param name="existingValue">The existing value of the object being read.</param>
        /// <param name="serializer">The calling serializer.</param>
        public override Object ReadJson(JsonReader reader, Type objectType, Object existingValue, JsonSerializer serializer)
        {
            if (!reader.CanReadObject())
                return null;

            var aggregateId = Guid.Empty;
            var command = default(Command);
            while (reader.Read() && reader.TokenType != JsonToken.EndObject)
            {
                String propertyName;
                if (!reader.TryGetProperty(out propertyName))
                    continue;

                switch (propertyName)
                {
                    case "a":
                        aggregateId = serializer.Deserialize<Guid>(reader);
                        break;
                    case "c":
                        command = serializer.Deserialize<Command>(reader);
                        break;
                }
            }

            return new CommandEnvelope(aggregateId, command);
        }
Ejemplo n.º 11
0
		public override void Copy(ODataObject source, JsonSerializer serializer)
		{
			if(source == null || serializer == null) return;
			base.Copy(source, serializer);

			var typedSource = source as AccessControlParam;
			if(typedSource != null)
			{
				AccessControl = typedSource.AccessControl;
				NotifyUser = typedSource.NotifyUser;
				NotifyMessage = typedSource.NotifyMessage;
				Recursive = typedSource.Recursive;
			}
			else
			{
				JToken token;
				if(source.TryGetProperty("AccessControl", out token) && token.Type != JTokenType.Null)
				{
					AccessControl = (AccessControl)serializer.Deserialize(token.CreateReader(), typeof(AccessControl));
				}
				if(source.TryGetProperty("NotifyUser", out token) && token.Type != JTokenType.Null)
				{
					NotifyUser = (bool?)serializer.Deserialize(token.CreateReader(), typeof(bool?));
				}
				if(source.TryGetProperty("NotifyMessage", out token) && token.Type != JTokenType.Null)
				{
					NotifyMessage = (string)serializer.Deserialize(token.CreateReader(), typeof(string));
				}
				if(source.TryGetProperty("Recursive", out token) && token.Type != JTokenType.Null)
				{
					Recursive = (bool?)serializer.Deserialize(token.CreateReader(), typeof(bool?));
				}
			}
		}
Ejemplo n.º 12
0
		public override void Copy(ODataObject source, JsonSerializer serializer)
		{
			if(source == null || serializer == null) return;
			base.Copy(source, serializer);

			var typedSource = source as DiskSpace;
			if(typedSource != null)
			{
				Max = typedSource.Max;
				Used = typedSource.Used;
				Free = typedSource.Free;
			}
			else
			{
				JToken token;
				if(source.TryGetProperty("Max", out token) && token.Type != JTokenType.Null)
				{
					Max = (int?)serializer.Deserialize(token.CreateReader(), typeof(int?));
				}
				if(source.TryGetProperty("Used", out token) && token.Type != JTokenType.Null)
				{
					Used = (int?)serializer.Deserialize(token.CreateReader(), typeof(int?));
				}
				if(source.TryGetProperty("Free", out token) && token.Type != JTokenType.Null)
				{
					Free = (int?)serializer.Deserialize(token.CreateReader(), typeof(int?));
				}
			}
		}
Ejemplo n.º 13
0
		public override void Copy(ODataObject source, JsonSerializer serializer)
		{
			if(source == null || serializer == null) return;
			base.Copy(source, serializer);

			var typedSource = source as DeviceUserWipe;
			if(typedSource != null)
			{
				WipeToken = typedSource.WipeToken;
				Success = typedSource.Success;
				ErrorMessage = typedSource.ErrorMessage;
			}
			else
			{
				JToken token;
				if(source.TryGetProperty("WipeToken", out token) && token.Type != JTokenType.Null)
				{
					WipeToken = (string)serializer.Deserialize(token.CreateReader(), typeof(string));
				}
				if(source.TryGetProperty("Success", out token) && token.Type != JTokenType.Null)
				{
					Success = (string)serializer.Deserialize(token.CreateReader(), typeof(string));
				}
				if(source.TryGetProperty("ErrorMessage", out token) && token.Type != JTokenType.Null)
				{
					ErrorMessage = (string)serializer.Deserialize(token.CreateReader(), typeof(string));
				}
			}
		}
Ejemplo n.º 14
0
        public override void Copy(ODataObject source, JsonSerializer serializer)
        {
            if(source == null || serializer == null) return;
            base.Copy(source, serializer);

            var typedSource = source as FindSubdomainParams;
            if(typedSource != null)
            {
                UsernameShort = typedSource.UsernameShort;
                Password = typedSource.Password;
                EmployeeOnly = typedSource.EmployeeOnly;
            }
            else
            {
                JToken token;
                if(source.TryGetProperty("UsernameShort", out token) && token.Type != JTokenType.Null)
                {
                    UsernameShort = (string)serializer.Deserialize(token.CreateReader(), typeof(string));
                }
                if(source.TryGetProperty("Password", out token) && token.Type != JTokenType.Null)
                {
                    Password = (string)serializer.Deserialize(token.CreateReader(), typeof(string));
                }
                if(source.TryGetProperty("EmployeeOnly", out token) && token.Type != JTokenType.Null)
                {
                    EmployeeOnly = (bool)serializer.Deserialize(token.CreateReader(), typeof(bool));
                }
            }
        }
Ejemplo n.º 15
0
        public override async Task<CreditInfo> RetrieveCreditInfo(string username, string password, string Type, Guid dev_id)
        {

            var dsrz = new JsonSerializer();
            using (var httpclient = new HttpClient())
            {
                httpclient.DefaultRequestHeaders.ExpectContinue = false;
                httpclient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/bson"));
                using (var httpstrAuthJson = await httpclient.PostAsync("https://wauth.apphb.com/api/AuthServ/GetData", new StringContent(JsonConvert.SerializeObject(new { q = username, x = password, t = Type, dev_id = dev_id }), Encoding.UTF8, "application/json")))
                {
                    using (var strData = await httpstrAuthJson.Content.ReadAsStreamAsync())
                    {

                        var bson = new BsonReader(strData);

                        if (httpstrAuthJson.StatusCode == HttpStatusCode.BadRequest)
                        {
                            var obj = dsrz.Deserialize<MessageError>(bson);
                            throw new Exception(obj.Message);
                        }

                        if (httpstrAuthJson.StatusCode == HttpStatusCode.NotFound)
                        {
                            var obj = new { Message = "Error during server connection." };
                            throw new Exception(obj.Message);
                        }

                        httpstrAuthJson.RequestMessage.Content.Dispose();
                        return dsrz.Deserialize<CreditInfo>(bson);
                    }


                }
            }
        }
Ejemplo n.º 16
0
		public override void Copy(ODataObject source, JsonSerializer serializer)
		{
			if(source == null || serializer == null) return;
			base.Copy(source, serializer);

			var typedSource = source as ShareItemHistory;
			if(typedSource != null)
			{
				Title = typedSource.Title;
				Recipient = typedSource.Recipient;
				ActivityType = typedSource.ActivityType;
				DownloadDate = typedSource.DownloadDate;
			}
			else
			{
				JToken token;
				if(source.TryGetProperty("Title", out token) && token.Type != JTokenType.Null)
				{
					Title = (string)serializer.Deserialize(token.CreateReader(), typeof(string));
				}
				if(source.TryGetProperty("Recipient", out token) && token.Type != JTokenType.Null)
				{
					Recipient = (string)serializer.Deserialize(token.CreateReader(), typeof(string));
				}
				if(source.TryGetProperty("ActivityType", out token) && token.Type != JTokenType.Null)
				{
					ActivityType = (SafeEnum<ItemAction>)serializer.Deserialize(token.CreateReader(), typeof(SafeEnum<ItemAction>));
				}
				if(source.TryGetProperty("DownloadDate", out token) && token.Type != JTokenType.Null)
				{
					DownloadDate = (DateTime?)serializer.Deserialize(token.CreateReader(), typeof(DateTime?));
				}
			}
		}
        public override void Copy(ODataObject source, JsonSerializer serializer)
        {
            if(source == null || serializer == null) return;
            base.Copy(source, serializer);

            var typedSource = source as ConnectorGroupAccessControl;
            if(typedSource != null)
            {
                Principal = typedSource.Principal;
                CanManage = typedSource.CanManage;
                CanCreate = typedSource.CanCreate;
            }
            else
            {
                JToken token;
                if(source.TryGetProperty("Principal", out token) && token.Type != JTokenType.Null)
                {
                    Principal = (Principal)serializer.Deserialize(token.CreateReader(), typeof(Principal));
                }
                if(source.TryGetProperty("CanManage", out token) && token.Type != JTokenType.Null)
                {
                    CanManage = (bool?)serializer.Deserialize(token.CreateReader(), typeof(bool?));
                }
                if(source.TryGetProperty("CanCreate", out token) && token.Type != JTokenType.Null)
                {
                    CanCreate = (bool?)serializer.Deserialize(token.CreateReader(), typeof(bool?));
                }
            }
        }
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            var json = JObject.ReadFrom(reader) as JObject;
            if (json == null || json.Type == JTokenType.Null)
                return null;
            var response = new GraphProjectResponse() { Nodes = new List<GraphNode>() };
            // Parse the status
            JToken value = null;
            json.TryGetValue("status", out value);
            response.Status = serializer.Deserialize<Status>(value.CreateReader());
            if (response.Status.IsSuccessful == false)
                return response;

            // Parse the nodes
            var root = json.Properties().SingleOrDefault( p => p.Name != "status");
            if (root == null || root.Value.Type != JTokenType.Object)
                return response;
            var rootObject = root.Value as JObject;
            if (rootObject == null)
                return response;
            var valuesProperty = rootObject.Property("values");
            if (valuesProperty == null || valuesProperty.Value.Type != JTokenType.Array)
                return response;
            var nodeJsons = valuesProperty.Values().Select(x => x as JObject);
            foreach (var nodeJson in nodeJsons)
            {
                var node = serializer.Deserialize<GraphNode>(nodeJson.CreateReader());
                response.Nodes.Add(node);
            }


            return response;    
        }
Ejemplo n.º 19
0
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            if (reader.ValueType == typeof(bool))
            {
                bool sourceEnabled = (bool)reader.Value;
                if (!sourceEnabled)
                    return new SourceFilter();
                else
                    return null;
            }
            else if (reader.ValueType == typeof(string))
            {
                return new SourceFilter(reader.Value.ToString());
            }
            else if (reader.TokenType == JsonToken.StartArray)
            {
                return new SourceFilter(serializer.Deserialize<IEnumerable<string>>(reader));
            }

            Dictionary<string, object> fieldDict = serializer.Deserialize<Dictionary<string, object>>(reader);
            if (fieldDict.ContainsKey(SearchPieceTypeEnum.SourceFilter.ToString()))
                fieldDict = JsonConvert.DeserializeObject<Dictionary<string, object>>(fieldDict.First().Value.ToString());

            return new SourceFilter(
                JsonConvert.DeserializeObject<IEnumerable<string>>(fieldDict.GetString(_INCLUDE)),
                JsonConvert.DeserializeObject<IEnumerable<string>>(fieldDict.GetString(_EXCLUDE)));            
        }
Ejemplo n.º 20
0
		public override void Copy(ODataObject source, JsonSerializer serializer)
		{
			if(source == null || serializer == null) return;
			base.Copy(source, serializer);

			var typedSource = source as PowerTools;
			if(typedSource != null)
			{
				EnableDesktopToolsPage = typedSource.EnableDesktopToolsPage;
				EnableMobileApps = typedSource.EnableMobileApps;
				ShowMobileTools = typedSource.ShowMobileTools;
			}
			else
			{
				JToken token;
				if(source.TryGetProperty("EnableDesktopToolsPage", out token) && token.Type != JTokenType.Null)
				{
					EnableDesktopToolsPage = (bool)serializer.Deserialize(token.CreateReader(), typeof(bool));
				}
				if(source.TryGetProperty("EnableMobileApps", out token) && token.Type != JTokenType.Null)
				{
					EnableMobileApps = (bool)serializer.Deserialize(token.CreateReader(), typeof(bool));
				}
				if(source.TryGetProperty("ShowMobileTools", out token) && token.Type != JTokenType.Null)
				{
					ShowMobileTools = (bool)serializer.Deserialize(token.CreateReader(), typeof(bool));
				}
			}
		}
Ejemplo n.º 21
0
		public override void Copy(ODataObject source, JsonSerializer serializer)
		{
			if(source == null || serializer == null) return;
			base.Copy(source, serializer);

			var typedSource = source as FolderTemplateItem;
			if(typedSource != null)
			{
				Name = typedSource.Name;
				Description = typedSource.Description;
				Items = typedSource.Items;
			}
			else
			{
				JToken token;
				if(source.TryGetProperty("Name", out token) && token.Type != JTokenType.Null)
				{
					Name = (string)serializer.Deserialize(token.CreateReader(), typeof(string));
				}
				if(source.TryGetProperty("Description", out token) && token.Type != JTokenType.Null)
				{
					Description = (string)serializer.Deserialize(token.CreateReader(), typeof(string));
				}
				if(source.TryGetProperty("Items", out token) && token.Type != JTokenType.Null)
				{
					Items = (IEnumerable<FolderTemplateItem>)serializer.Deserialize(token.CreateReader(), typeof(IEnumerable<FolderTemplateItem>));
				}
			}
		}
Ejemplo n.º 22
0
        public override void Copy(ODataObject source, JsonSerializer serializer)
        {
            if(source == null || serializer == null) return;
            base.Copy(source, serializer);

            var typedSource = source as FileLock;
            if(typedSource != null)
            {
                LockId = typedSource.LockId;
                LockType = typedSource.LockType;
                Owner = typedSource.Owner;
                ExpirationTimeInMinutes = typedSource.ExpirationTimeInMinutes;
            }
            else
            {
                JToken token;
                if(source.TryGetProperty("LockId", out token) && token.Type != JTokenType.Null)
                {
                    LockId = (string)serializer.Deserialize(token.CreateReader(), typeof(string));
                }
                if(source.TryGetProperty("LockType", out token) && token.Type != JTokenType.Null)
                {
                    LockType = (SafeEnum<LockType>)serializer.Deserialize(token.CreateReader(), typeof(SafeEnum<LockType>));
                }
                if(source.TryGetProperty("Owner", out token) && token.Type != JTokenType.Null)
                {
                    Owner = (Principal)serializer.Deserialize(token.CreateReader(), typeof(Principal));
                }
                if(source.TryGetProperty("ExpirationTimeInMinutes", out token) && token.Type != JTokenType.Null)
                {
                    ExpirationTimeInMinutes = (int?)serializer.Deserialize(token.CreateReader(), typeof(int?));
                }
            }
        }
        /// <summary>
        /// Reads the JSON representation of a <see cref="CommitData"/> instance.
        /// </summary>
        /// <param name="reader">The <see cref="JsonReader"/> to read from.</param>
        /// <param name="objectType">The type of object.</param>
        /// <param name="existingValue">The existing value of the object being read.</param>
        /// <param name="serializer">The calling serializer.</param>
        public override Object ReadJson(JsonReader reader, Type objectType, Object existingValue, JsonSerializer serializer)
        {
            if (!reader.CanReadObject())
                return CommitData.Empty;

            var events = EventCollection.Empty;
            var headers = HeaderCollection.Empty;
            while (reader.Read() && reader.TokenType != JsonToken.EndObject)
            {
                String propertyName;
                if (!reader.TryGetProperty(out propertyName))
                    continue;

                switch (propertyName)
                {
                    case "h":
                        headers = serializer.Deserialize<HeaderCollection>(reader);
                        break;
                    case "e":
                        events = serializer.Deserialize<EventCollection>(reader);
                        break;
                }
            }

            return new CommitData(headers, events);
        }
Ejemplo n.º 24
0
        public override void Copy(ODataObject source, JsonSerializer serializer)
        {
            if(source == null || serializer == null) return;
            base.Copy(source, serializer);

            var typedSource = source as Metadata;
            if(typedSource != null)
            {
                Name = typedSource.Name;
                Value = typedSource.Value;
                IsPublic = typedSource.IsPublic;
            }
            else
            {
                JToken token;
                if(source.TryGetProperty("Name", out token) && token.Type != JTokenType.Null)
                {
                    Name = (string)serializer.Deserialize(token.CreateReader(), typeof(string));
                }
                if(source.TryGetProperty("Value", out token) && token.Type != JTokenType.Null)
                {
                    Value = (string)serializer.Deserialize(token.CreateReader(), typeof(string));
                }
                if(source.TryGetProperty("IsPublic", out token) && token.Type != JTokenType.Null)
                {
                    IsPublic = (bool?)serializer.Deserialize(token.CreateReader(), typeof(bool?));
                }
            }
        }
		public override void Copy(ODataObject source, JsonSerializer serializer)
		{
			if(source == null || serializer == null) return;
			base.Copy(source, serializer);

			var typedSource = source as AccessControlFailedEntry;
			if(typedSource != null)
			{
				AccessControl = typedSource.AccessControl;
				Code = typedSource.Code;
				Message = typedSource.Message;
			}
			else
			{
				JToken token;
				if(source.TryGetProperty("AccessControl", out token) && token.Type != JTokenType.Null)
				{
					AccessControl = (AccessControl)serializer.Deserialize(token.CreateReader(), typeof(AccessControl));
				}
				if(source.TryGetProperty("Code", out token) && token.Type != JTokenType.Null)
				{
					Code = (SafeEnum<HttpStatusCode>)serializer.Deserialize(token.CreateReader(), typeof(SafeEnum<HttpStatusCode>));
				}
				if(source.TryGetProperty("Message", out token) && token.Type != JTokenType.Null)
				{
					Message = (ODataExceptionMessage)serializer.Deserialize(token.CreateReader(), typeof(ODataExceptionMessage));
				}
			}
		}
        /// <summary>
        /// Reads the JSON representation of a <see cref="EventCollection"/> instance.
        /// </summary>
        /// <param name="reader">The <see cref="JsonReader"/> to read from.</param>
        /// <param name="objectType">The type of object.</param>
        /// <param name="existingValue">The existing value of the object being read.</param>
        /// <param name="serializer">The calling serializer.</param>
        public override Object ReadJson(JsonReader reader, Type objectType, Object existingValue, JsonSerializer serializer)
        {
            if (!reader.CanReadObject())
                return null;

            var id = Guid.Empty;
            var payload = default(Object);
            var headers = HeaderCollection.Empty;
            var payloadType = KnownPayloadTypes[objectType];
            while (reader.Read() && reader.TokenType != JsonToken.EndObject)
            {
                String propertyName;
                if (!reader.TryGetProperty(out propertyName))
                    continue;

                switch (propertyName)
                {
                    case "id":
                        id = serializer.Deserialize<Guid>(reader);
                        break;
                    case "h":
                        headers = serializer.Deserialize<HeaderCollection>(reader);
                        break;
                    case "p":
                        payload = serializer.Deserialize(reader, payloadType);
                        break;
                }
            }

            return Activator.CreateInstance(objectType, id, headers, payload);
        }
Ejemplo n.º 27
0
 /// <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)
 {
     reader.Read();
     if (!(reader.TokenType == JsonToken.PropertyName && (string) reader.Value == "type"))
         throw new ArgumentException("Expected token 'type' not found.");
     reader.Read();
     if (reader.TokenType != JsonToken.String && (string) reader.Value != "Feature")
         throw new ArgumentException("Expected value 'Feature' not found.");
     reader.Read();
     if (!(reader.TokenType == JsonToken.PropertyName && (string) reader.Value == "geometry"))
         throw new ArgumentException("Expected token 'geometry' not found.");
     reader.Read();
     if (reader.TokenType != JsonToken.StartObject)
         throw new ArgumentException("Expected token '{' not found.");
     Feature feature = new Feature {Geometry = serializer.Deserialize<Geometry>(reader)};
     if (reader.TokenType != JsonToken.EndObject)
         throw new ArgumentException("Expected token '}' not found.");
     reader.Read();
     if (reader.TokenType == JsonToken.PropertyName && (string) reader.Value == "properties")
         feature.Attributes = serializer.Deserialize<AttributesTable>(reader);
     if (reader.TokenType != JsonToken.EndObject)
         throw new ArgumentException("Expected token '}' not found.");
     reader.Read();
     return feature;
 }
        /// <summary>
        /// Reads the JSON representation of an <see cref="StateObject"/> instance.
        /// </summary>
        /// <param name="reader">The <see cref="JsonReader"/> to read from.</param>
        /// <param name="objectType">The type of object.</param>
        /// <param name="existingValue">The existing value of the object being read.</param>
        /// <param name="serializer">The calling serializer.</param>
        public override Object ReadJson(JsonReader reader, Type objectType, Object existingValue, JsonSerializer serializer)
        {
            if (!reader.CanReadObject())
                return null;

            var stateObject = default(StateObject);
            var state = new Dictionary<String, Object>();
            while (reader.Read() && reader.TokenType != JsonToken.EndObject)
            {
                var propertyName = String.Empty;
                if (!reader.TryGetProperty(out propertyName))
                    continue;

                if (propertyName == TypePropertyName)
                {
                    objectType = Type.GetType(serializer.Deserialize<String>(reader), throwOnError: true, ignoreCase: true);
                    stateObject = (StateObject)FormatterServices.GetUninitializedObject(objectType);
                }
                else
                {
                    stateObject = stateObject ?? (StateObject)FormatterServices.GetUninitializedObject(objectType);
                    state.Add(propertyName, serializer.Deserialize(reader, stateObject.GetFieldType(propertyName)));
                }
            }

            stateObject?.SetState(state);

            return stateObject;
        }
        /// <summary>
        /// Reads the JSON representation of an <see cref="EventEnvelope"/> instance.
        /// </summary>
        /// <param name="reader">The <see cref="JsonReader"/> to read from.</param>
        /// <param name="objectType">The type of object.</param>
        /// <param name="existingValue">The existing value of the object being read.</param>
        /// <param name="serializer">The calling serializer.</param>
        public override Object ReadJson(JsonReader reader, Type objectType, Object existingValue, JsonSerializer serializer)
        {
            if (!reader.CanReadObject())
                return null;

            var e = default(Event);
            var aggregateId = Guid.Empty;
            var correlationId = Guid.Empty;
            var version = EventVersion.Empty;
            while (reader.Read() && reader.TokenType != JsonToken.EndObject)
            {
                String propertyName;
                if (!reader.TryGetProperty(out propertyName))
                    continue;

                switch (propertyName)
                {
                    case "a":
                        aggregateId = serializer.Deserialize<Guid>(reader);
                        break;
                    case "v":
                        version = serializer.Deserialize<EventVersion>(reader);
                        break;
                    case "e":
                        e = serializer.Deserialize<Event>(reader);
                        break;
                    case "c":
                        correlationId = serializer.Deserialize<Guid>(reader);
                        break;
                }
            }

            return new EventEnvelope(correlationId, aggregateId, version, e);
        }
Ejemplo n.º 30
0
        public override void Copy(ODataObject source, JsonSerializer serializer)
        {
            if(source == null || serializer == null) return;
            base.Copy(source, serializer);

            var typedSource = source as MarketAnalytics;
            if(typedSource != null)
            {
                ConversionIndex = typedSource.ConversionIndex;
                ConversionIndex2 = typedSource.ConversionIndex2;
                LtvIndex = typedSource.LtvIndex;
                PlanValue = typedSource.PlanValue;
            }
            else
            {
                JToken token;
                if(source.TryGetProperty("ConversionIndex", out token) && token.Type != JTokenType.Null)
                {
                    ConversionIndex = (decimal?)serializer.Deserialize(token.CreateReader(), typeof(decimal?));
                }
                if(source.TryGetProperty("ConversionIndex2", out token) && token.Type != JTokenType.Null)
                {
                    ConversionIndex2 = (decimal?)serializer.Deserialize(token.CreateReader(), typeof(decimal?));
                }
                if(source.TryGetProperty("LtvIndex", out token) && token.Type != JTokenType.Null)
                {
                    LtvIndex = (decimal?)serializer.Deserialize(token.CreateReader(), typeof(decimal?));
                }
                if(source.TryGetProperty("PlanValue", out token) && token.Type != JTokenType.Null)
                {
                    PlanValue = (decimal?)serializer.Deserialize(token.CreateReader(), typeof(decimal?));
                }
            }
        }
Ejemplo n.º 31
0
        public async Task <IGraph> Deserialize(Stream stream, CancellationToken ct = default(CancellationToken))
        {
            JObject jobject;

            using (var reader = new StreamReader(stream))
                using (var j = new JsonTextReader(reader))
                {
                    jobject = await Task.Factory.StartNew(() => serializer.Deserialize <JObject>(j), ct);
                }

            if (ct.IsCancellationRequested)
            {
                return(null);
            }

            return(this.Deserialize(jobject));
        }
Ejemplo n.º 32
0
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, Newtonsoft.Json.JsonSerializer serializer)
        {
            TwitterMediaProcessingState retVal = TwitterMediaProcessingState.Pending;

            var enumStringValue = serializer.Deserialize(reader).ToString();

            if (enumStringValue == "in_progress")
            {
                retVal = TwitterMediaProcessingState.InProgress;
            }
            else
            {
                retVal = (TwitterMediaProcessingState)System.Enum.Parse(typeof(TwitterMediaProcessingState), enumStringValue, true);
            }

            return(retVal);
        }
        public override object ReadJson(
            JsonReader reader, Type objectType,
            object existingValue, Newtonsoft.Json.JsonSerializer serializer)
        {
            var restore = new { serializer.Binder, serializer.MetadataPropertyHandling };

            serializer.Binder = new Binder(restore.Binder, collectionType, typeof(ExtendedEnumerableSurrogate));
            serializer.MetadataPropertyHandling = MetadataPropertyHandling.Ignore;
            var surrogate = serializer.Deserialize <ExtendedEnumerableSurrogate>(reader);

            serializer.Binder = restore.Binder;
            serializer.MetadataPropertyHandling = restore.MetadataPropertyHandling;

            var result = new CollectionFactory(serializer).Create(surrogate);

            return(result);
        }
Ejemplo n.º 34
0
    public void bindKioskDetails()
    {
        try
        {
            if (objds == null)
            {
                objds = new DataSet();
            }

            Reply objRes = new Reply();
            // send request
            using (WebClient client = new WebClient())
            {
                client.Headers[HttpRequestHeader.ContentType] = "text/json";

                string     JsonString    = JsonConvert.SerializeObject("KioskList");
                EncRequest objEncRequest = new EncRequest();
                objEncRequest.RequestData = AesGcm256.Encrypt(JsonString);
                string dataEncrypted = JsonConvert.SerializeObject(objEncRequest);

                string result = client.UploadString(URL + "/GetKioskMasterList", "POST", dataEncrypted);

                EncResponse objResponse = JsonConvert.DeserializeObject <EncResponse>(result);
                objResponse.ResponseData = AesGcm256.Decrypt(objResponse.ResponseData);
                Newtonsoft.Json.JsonSerializer json = new Newtonsoft.Json.JsonSerializer();
                json.NullValueHandling = NullValueHandling.Ignore;
                StringReader sr = new StringReader(objResponse.ResponseData);
                Newtonsoft.Json.JsonTextReader reader = new JsonTextReader(sr);
                objRes = json.Deserialize <Reply>(reader);

                if (objRes.res == true)
                {
                    //Data Source
                    GV_Kiosk_Details.DataSource = objRes.DS;
                    GV_Kiosk_Details.DataBind();
                }
                else
                {
                    Response.Write("<script type='text/javascript'>alert('" + objRes.strError + "')</script>");
                }
            }
        }
        catch (Exception excp)
        {
        }
    }
Ejemplo n.º 35
0
            public T Deserialize <T>(IRestResponse response)
            {
                if (response.StatusCode != HttpStatusCode.OK)
                {
                    return(default(T));
                }

                var content = response.Content;

                using (var stringReader = new StringReader(content))
                {
                    using (var jsonTextReader = new JsonTextReader(stringReader))
                    {
                        return(_serializer.Deserialize <T>(jsonTextReader));
                    }
                }
            }
Ejemplo n.º 36
0
        //private void ViewData()
        //{
        //	HttpWebRequest req = common.connectionGet("people");

        //	HttpWebResponse res = (HttpWebResponse)req.GetResponse();
        //	List<PersonView> result;
        //	using (res)
        //	{
        //		using (var resStream = res.GetResponseStream())
        //		{
        //			StreamReader sr = new StreamReader(resStream);
        //			string str = sr.ReadToEnd();
        //			result = JsonConvert.DeserializeObject<List<PersonView>>(str.ToString());
        //		}
        //	}
        //	ViewGrid.DataContext = common.ConvertToDataTable(result);

        //}

        //private void PostData(PersonView data)
        //{
        //	HttpWebRequest req = common.connectionPost("people");

        //	using (var streamWriter = new StreamWriter(req.GetRequestStream()))
        //	{
        //		string json = Newtonsoft.Json.JsonConvert.SerializeObject(data);
        //		streamWriter.Write(json);
        //	}

        //	HttpWebResponse res = (HttpWebResponse)req.GetResponse();
        //	List<PersonView> result = new List<PersonView>();
        //	using (res)
        //	{
        //		using (var resStream = res.GetResponseStream())
        //		{
        //			StreamReader sr = new StreamReader(resStream);
        //			string str = sr.ReadToEnd();
        //			var r = JsonConvert.DeserializeObject<PersonView>(str.ToString());
        //			result.Add(r);
        //		}
        //	}
        //	ViewGrid.DataContext = common.ConvertToDataTable(result);
        //}
        //

        //private void PostDataList(List<PersonView> data)
        //{
        //	HttpWebRequest req = common.connectionPost("people");

        //	using (var streamWriter = new StreamWriter(req.GetRequestStream()))
        //	{
        //		string json = Newtonsoft.Json.JsonConvert.SerializeObject(data);
        //		streamWriter.Write(json);
        //	}

        //	HttpWebResponse res = (HttpWebResponse)req.GetResponse();
        //	List<PersonView> result = new List<PersonView>();
        //	using (res)
        //	{
        //		using (var resStream = res.GetResponseStream())
        //		{
        //			StreamReader sr = new StreamReader(resStream);
        //			string str = sr.ReadToEnd();
        //			var r = JsonConvert.DeserializeObject<PersonView>(str.ToString());
        //			result.Add(r);
        //		}
        //	}
        //	ViewGrid.DataContext = common.ConvertToDataTable(result);
        //}


        //private void Button_Click(object sender, RoutedEventArgs e)
        //{
        //	DataTable table = ViewGrid.DataContext as DataTable;
        //	DataTable list = table.GetChanges();
        //	foreach (PersonView item in list.Rows)
        //	{
        //		PostData(item);
        //	}
        //}
        #endregion



        #region API処理

        private async void GetUserList()
        {
            var hc = new HttpClient();

            hc.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            var res = await hc.GetAsync(common.GetURL() + "people");

            var str = await res.Content.ReadAsStringAsync();

            testMess.Text = str;

            var js    = new Newtonsoft.Json.JsonSerializer();
            var jr    = new Newtonsoft.Json.JsonTextReader(new System.IO.StringReader(str));
            var items = js.Deserialize <List <PersonView> >(jr);

            ViewGrid.ItemsSource = items;
        }
Ejemplo n.º 37
0
        private static (object, bool) ExtractRequest(object payload)
        {
            if (payload == null)
            {
                throw new ArgumentException("The request payload is missing.");
            }

            return(payload switch
            {
                JsonElement json => /* System.Text.Json */
                (JsonConvert.DeserializeObject(json.GetRawText(),
                                               HttpFormatters.Route.SerializerSettings), true),
                JObject json =>     /* Newtonsoft.Json */
                (JsonSerializer.Deserialize(new JTokenReader(json)), false),
                _ => throw new InvalidOperationException(
                    $"Unrecognized payload type '{payload.GetType().FullName}.'")
            });
Ejemplo n.º 38
0
 public T Deserialize <T>(RestSharp.IRestResponse response)
 {
     try
     {
         using (var stringReader = new StringReader(response.Content))
         {
             using (var jsonTextReader = new JsonTextReader(stringReader))
             {
                 return(Serializer.Deserialize <T>(jsonTextReader));
             }
         }
     }
     catch (Exception)
     {
         return(default(T));
     }
 }
Ejemplo n.º 39
0
 /// <summary>
 /// 从文件反序列对象
 /// </summary>
 /// <typeparam name="T"></typeparam>
 /// <param name="filename"></param>
 /// <returns></returns>
 public T DeSerializFromFile <T>(string filename)
 {
     if (string.IsNullOrEmpty(filename))
     {
         throw new ArgumentNullException(nameof(filename), "filename can't be empty.");
     }
     if (!File.Exists(filename))
     {
         throw new ArgumentNullException(nameof(filename), "filename doesn't exists.");
     }
     Newtonsoft.Json.JsonSerializer serializer = new Newtonsoft.Json.JsonSerializer();
     using (var file = new StreamReader(filename, Utf8))
         using (var reader = new JsonTextReader(file))
         {
             return(serializer.Deserialize <T>(reader));
         }
 }
Ejemplo n.º 40
0
        public static List <Definition> GetDefinitions(string word)
        {
            var results   = new List <Definition>();
            var webClient = new WebClient();

            webClient.Headers.Add("x-rapidapi-key", "f0063a9c50mshe67bf3e784124c3p14f28ajsnd35df8e9ddb0");
            byte[] definitions = webClient.DownloadData(string.Format("https://wordsapiv1.p.rapidapi.com/words/{0}/definitions", word));
            var    serializer  = new JsonSerializer();

            using (var stream = new MemoryStream(definitions))
                using (var reader = new StreamReader(stream))
                    using (var jsonReader = new JsonTextReader(reader))
                    {
                        results = serializer.Deserialize <Dictionary>(jsonReader).definitions;
                    }
            return(results);
        }
Ejemplo n.º 41
0
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, Newtonsoft.Json.JsonSerializer serializer)
        {
            TwitterMediaType retVal = TwitterMediaType.Photo;

            var enumStringValue = serializer.Deserialize(reader).ToString();

            if (enumStringValue == "animated_gif")
            {
                retVal = TwitterMediaType.AnimatedGif;
            }
            else
            {
                retVal = (TwitterMediaType)System.Enum.Parse(typeof(TwitterMediaType), enumStringValue, true);
            }

            return(retVal);
        }
Ejemplo n.º 42
0
 /// <summary>
 /// De-serialize an object from JSON.
 ///
 /// Returns: the de-serialized object
 ///
 /// Exceptions:
 ///   - IllegalArgumentException : if any argument is null
 ///   - JSONSerializationException : if there is any other error occurred during the operation
 /// </summary>
 /// <param name="inputStream"> the input stream from which the JSON will be read </param>
 /// <exception cref="Api.Internal.Json.JsonSerializationException"> </exception>
 public virtual T deserialize <T>(StreamReader inputStream)
 {
     Utils.ThrowIfNull(inputStream);
     try
     {
         return(serializer.Deserialize <T>(new Newtonsoft.Json.JsonTextReader(inputStream)));
     }
     catch (Newtonsoft.Json.JsonException ex)
     {
         throw new JsonSerializationException(ex);
     }
     catch (IOException ex)
     {
         throw new JsonSerializationException(ex);
     }
 }
 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
                     }
                 }
             }
         }
         return(error);
     }
     return(null);
 }
Ejemplo n.º 44
0
        /// <summary>
        /// 将Json数据转为对象(C# json 转换其他格式)
        /// </summary>
        /// <typeparam name="T">目标对象</typeparam>
        /// <param name="jsonText">json数据字符串</param>
        /// <returns></returns>
        public static T FromJson <T>(this string jsonText)
        {
            Newtonsoft.Json.JsonSerializer json = new Newtonsoft.Json.JsonSerializer();

            json.NullValueHandling      = Newtonsoft.Json.NullValueHandling.Ignore;
            json.ObjectCreationHandling = Newtonsoft.Json.ObjectCreationHandling.Replace;
            json.MissingMemberHandling  = Newtonsoft.Json.MissingMemberHandling.Ignore;
            json.ReferenceLoopHandling  = Newtonsoft.Json.ReferenceLoopHandling.Ignore;

            StringReader sr = new StringReader(jsonText);

            Newtonsoft.Json.JsonTextReader reader = new JsonTextReader(sr);
            T result = (T)json.Deserialize(reader, typeof(T));

            reader.Close();

            return(result);
        }
Ejemplo n.º 45
0
        public static List <IFigures> Deserilization(string filename)
        {
            var serializer = new Newtonsoft.Json.JsonSerializer
            {
                TypeNameHandling = Newtonsoft.Json.TypeNameHandling.Auto
            };

            List <IFigures> _figure = null;

            using (StreamReader streamReader = new StreamReader(filename))
            {
                using (Newtonsoft.Json.JsonReader jreader = new Newtonsoft.Json.JsonTextReader(streamReader))
                {
                    _figure = serializer.Deserialize <List <IFigures> >(jreader);
                }
            }
            return(_figure);
        }
Ejemplo n.º 46
0
        public static void LoadField(string mapName)
        {
            Field field = new Field();

            Console.Clear();
            var settings = new JsonSerializerSettings {
                TypeNameHandling = TypeNameHandling.Auto, Formatting = Formatting.Indented
            };
            string projectDirectory = Directory.GetParent(System.Environment.CurrentDirectory)?.Parent?.FullName;

            using (StreamReader file = File.OpenText($@"{projectDirectory}\maps\{mapName}.json"))
            {
                Newtonsoft.Json.JsonSerializer serializer = Newtonsoft.Json.JsonSerializer.Create(settings);
                field = (Field)serializer.Deserialize(file, typeof(Field));
            }
            field.PrintField();
            PlayerControl(field);
        }
Ejemplo n.º 47
0
        /// <summary>
        /// 反序列化Json数据格式.
        /// </summary>
        /// <param name="jsonText">The json text.</param>
        /// <param name="valueType">Type of the value.</param>
        /// <returns></returns>
        public static object Deserialize(string jsonText, Type valueType)
        {
            Newtonsoft.Json.JsonSerializer json = new Newtonsoft.Json.JsonSerializer();

            json.NullValueHandling      = Newtonsoft.Json.NullValueHandling.Ignore;
            json.ObjectCreationHandling = Newtonsoft.Json.ObjectCreationHandling.Replace;
            json.MissingMemberHandling  = Newtonsoft.Json.MissingMemberHandling.Ignore;
            json.ReferenceLoopHandling  = Newtonsoft.Json.ReferenceLoopHandling.Ignore;

            StringReader sr = new StringReader(jsonText);

            Newtonsoft.Json.JsonTextReader reader = new JsonTextReader(sr);
            object result = json.Deserialize(reader, valueType);

            reader.Close();

            return(result);
        }
Ejemplo n.º 48
0
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, Newtonsoft.Json.JsonSerializer serializer)
        {
            var dict = serializer.Deserialize <Dictionary <string, object> >(reader);

            if (!dict.ContainsKey("type"))
            {
                return(null);
            }

            if (dict["type"].ToString().Equals("creditcard", StringComparison.InvariantCultureIgnoreCase))
            {
                return(JsonConvert.DeserializeObject <CreditCard>(JsonConvert.SerializeObject(dict)));
            }
            else
            {
                return(JsonConvert.DeserializeObject <Sadad>(JsonConvert.SerializeObject(dict)));
            }
        }
 public T Deserialize <T>(string json)
 {
     using (var stringReader = new StringReader(json))
     {
         using (var jsonTextReader = new JsonTextReader(stringReader))
         {
             try
             {
                 return(_serializer.Deserialize <T>(jsonTextReader));
             }
             catch (Exception ex)
             {
                 Logger.Error($"Couldn't deserialize json: {json}. Error: {ex}");
                 throw;
             }
         }
     }
 }
Ejemplo n.º 50
0
        public static async Task <T> ReadAsAsync <T>(this HttpContent content)
        {
            var contentStream = await content.ReadAsStreamAsync();

            using var streamReader = new StreamReader(contentStream);
            using var jsonReader   = new JsonTextReader(streamReader);

            var serializer = new Newtonsoft.Json.JsonSerializer();

            try
            {
                return(serializer.Deserialize <T>(jsonReader));
            }
            catch (JsonReaderException ex)
            {
                throw ex;
            }
        }
Ejemplo n.º 51
0
        public T Deserialize <T>(string data)
        {
            T deserializedType = default(T);

            if (!string.IsNullOrEmpty(data))
            {
                Newtonsoft.Json.JsonSerializer serializer = new Newtonsoft.Json.JsonSerializer();
                Initialize(serializer);

                using (StringReader reader = new StringReader(data))
                {
                    using (JsonTextReader jsonReader = new JsonTextReader(reader))
                    {
                        deserializedType = serializer.Deserialize <T>(jsonReader);
                    }
                }
            }
            return(deserializedType);
        }
Ejemplo n.º 52
0
        public async Task <Employee> AddEmployeeAsync(Employee empData)
        {
            response     = null;
            responseBody = null;
            //client.BaseAddress = new Uri("http://localhost:16061/");
            //client.DefaultRequestHeaders.Accept.Clear();
            //client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            response = await client.PostAsJsonAsync(
                "api/employees", empData);

            Employee emp = null;

            response.EnsureSuccessStatusCode();
            responseBody = await response.Content.ReadAsStringAsync();

            Newtonsoft.Json.JsonSerializer newSerilizer = new Newtonsoft.Json.JsonSerializer();
            emp = newSerilizer.Deserialize <Employee>(new JsonTextReader(new StringReader(responseBody)));
            return(emp);
        }
Ejemplo n.º 53
0
 public void OnInitialized(IContainerProvider containerProvider)
 {
     if (System.IO.File.Exists("database.json"))
     {
         JsonSerializer ser = new Newtonsoft.Json.JsonSerializer()
         {
             TypeNameHandling = TypeNameHandling.Auto
         };
         using (StreamReader re = new StreamReader("database.json"))
         {
             JsonTextReader reader = new JsonTextReader(re);
             DbAccess = ser.Deserialize <DbAccess>(reader);
         }
     }
     else
     {
         DbAccess = new DbAccess();
     }
 }
Ejemplo n.º 54
0
        protected override void InitValueExtractor()
        {
            // Init value extractor from first record

            ValueExtractor = new DictionaryExtractor(new string[] { }); // init empty first if can't init later

            Newtonsoft.Json.JsonSerializer oJsonSerializer = new Newtonsoft.Json.JsonSerializer();
            foreach (var st in StreamFactory.GetStreams(this.From, this.Recurse)) // returns touplse (stream name as string, Stream object implementaion)
            {
                using (AdvancedTextReader srdr = new AdvancedTextReader(st.Item2, this.TextReaderOptions))
                {
                    using (var m_JsonReader = new Newtonsoft.Json.JsonTextReader(srdr)
                    {
                        SupportMultipleContent = true
                    })
                    {
                        bool bStartRead = string.IsNullOrEmpty(JsonPropertyToRead);
                        while (m_JsonReader.Read())
                        {
                            if (!bStartRead && !(m_JsonReader.TokenType == JsonToken.PropertyName && m_JsonReader.Value == JsonPropertyToRead))
                            {
                                continue;
                            }
                            else
                            {
                                bStartRead = true;
                            }

                            if (m_JsonReader.TokenType == JsonToken.StartObject)
                            {
                                // Deserialize
                                JsonLogEntry logentry = oJsonSerializer.Deserialize <JsonLogEntry>(m_JsonReader);

                                // Set the value extractor from the first JSON record and exit
                                ValueExtractor = new DictionaryExtractor(logentry);

                                break;
                            }
                        }
                    }
                }
            }
        }
Ejemplo n.º 55
0
        protected System.Collections.Generic.IEnumerable <JsonLogEntry> GetEntries()
        {
            Newtonsoft.Json.JsonSerializer oJsonSerializer = new Newtonsoft.Json.JsonSerializer();
            foreach (System.Tuple <string, System.IO.Stream> st in StreamFactory.GetStreams(From, this.Recurse))
            {
                this.StreamLineNumber  = 0;
                this.CurrentStreamName = st.Item1;
                this.RecordIndex       = 0;

                using (AdvancedTextReader srdr = new AdvancedTextReader(st.Item2, this.TextReaderOptions))
                {
                    using (var m_JsonReader = new Newtonsoft.Json.JsonTextReader(srdr)
                    {
                        SupportMultipleContent = true
                    })
                    {
                        bool bStartRead = string.IsNullOrEmpty(JsonPropertyToRead);
                        while (m_JsonReader.Read())
                        {
                            if (!bStartRead && !(m_JsonReader.TokenType == JsonToken.PropertyName && m_JsonReader.Value == JsonPropertyToRead))
                            {
                                continue;
                            }
                            else
                            {
                                bStartRead = true;
                            }

                            if (m_JsonReader.TokenType == JsonToken.StartObject)
                            {
                                // Additional fields
                                this.StreamLineNumber = m_JsonReader.LineNumber;
                                this.RecordIndex     += 1;

                                // Deserialize entries and yield
                                JsonLogEntry le = oJsonSerializer.Deserialize <JsonLogEntry>(m_JsonReader);
                                yield return(le);
                            }
                        }
                    }
                }
            }
        }
 public void Initialize()
 {
     if (System.IO.File.Exists("solutions.json"))
     {
         JsonSerializer ser = new Newtonsoft.Json.JsonSerializer()
         {
             TypeNameHandling = TypeNameHandling.Auto
         };
         using (StreamReader re = new StreamReader("solutions.json"))
         {
             JsonTextReader reader = new JsonTextReader(re);
             ser.Deserialize <List <ISolutionItem> >(reader).ForEach((e) =>
             {
                 InitItem(e);
                 _items.Add(e);
             });
         }
     }
 }
Ejemplo n.º 57
0
        public virtual async Task <T> GetItemFromStream(Stream stream, CancellationToken ct = default)
        {
            var serializer = new JsonSerializer();

            using var streamReader = new StreamReader(stream);
            using var jsonReader   = new JsonTextReader(streamReader);

            await Task.CompletedTask;

            ICosmosItem <T> cosmosItem = default;

            while (jsonReader.Read())
            {
                cosmosItem = serializer.Deserialize <CosmosItem <T> >(jsonReader);
            }

            if (cosmosItem is null)
            {
                return(default);
Ejemplo n.º 58
0
        /// <summary>
        /// Deserializes a stream to a particular type.
        /// </summary>
        /// <typeparam name="T">Type of object to deserialize to.</typeparam>
        /// <param name="requestStream">Stream to serialize.</param>
        /// <returns>Deserialized object from stream.</returns>
        public T Deserialize <T>(Stream requestStream)
        {
            TextReader reader;

            if (debug)
            {
                var json = new StreamReader(requestStream).ReadToEnd();
                Console.WriteLine($"Lambda Deserialize {typeof(T).FullName}: {json}");
                reader = new StringReader(json);
            }
            else
            {
                reader = new StreamReader(requestStream);
            }

            JsonReader jsonReader = new JsonTextReader(reader);

            return(serializer.Deserialize <T>(jsonReader));
        }
Ejemplo n.º 59
0
        private static Dictionary <string, Entity> LoadMetadataFromFile(string[] files)
        {
            Dictionary <string, Entity> data = null;

            foreach (var file in files)
            {
                if (!File.Exists(file))
                {
                    ConsolePrinter.Write(ConsoleColor.Yellow, "Cannot find file {0}. Skipping...", file);
                    continue;
                }

                try
                {
                    var jsonSerSettings = new JsonSerializerSettings();
                    jsonSerSettings.TypeNameHandling = TypeNameHandling.All;
                    Newtonsoft.Json.JsonSerializer jsonSer = Newtonsoft.Json.JsonSerializer.CreateDefault(jsonSerSettings);

                    using (StreamReader sr = new StreamReader(file))
                        using (JsonReader jr = new JsonTextReader(sr))
                        {
                            ConsolePrinter.Write(ConsoleColor.White, "Loading metadata from file {0}", file);
                            var currentData = jsonSer.Deserialize <Dictionary <string, Entity> >(jr);

                            // If this is the first file, nothing to merge.
                            if (data == null)
                            {
                                data = currentData;
                                continue;
                            }

                            // we need to merge the 2 entities.
                            MergeMetadataInfo(data, currentData);
                        }
                }
                catch (Exception e)
                {
                    ConsolePrinter.Write(ConsoleColor.Red, "Error processing file {0} ({1}). Skipping.", file, e.Message);
                }
            }

            return(data);
        }
        public T Deserialize <T>(RestSharp.IRestResponse response)
        {
            var content = response.Content;

            using (var stringReader = new StringReader(content))
            {
                using (var jsonTextReader = new JsonTextReader(stringReader))
                {
                    try
                    {
                        return(serializer.Deserialize <T>(jsonTextReader));
                    }
                    catch (JsonReaderException e)
                    {
                        throw new JsonReaderException(string.Format("Problem deserialising the following {0} response from {1}, (see inner exception for further details): {2}", response.StatusCode, response.ResponseUri.OriginalString, content), e);
                    }
                }
            }
        }