コード例 #1
2
        public void Example()
        {
            #region Usage
            string json = @"{ 'name': 'Admin' }{ 'name': 'Publisher' }";

            IList<Role> roles = new List<Role>();

            JsonTextReader reader = new JsonTextReader(new StringReader(json));
            reader.SupportMultipleContent = true;

            while (true)
            {
                if (!reader.Read())
                    break;

                JsonSerializer serializer = new JsonSerializer();
                Role role = serializer.Deserialize<Role>(reader);

                roles.Add(role);
            }

            foreach (Role role in roles)
            {
                Console.WriteLine(role.Name);
            }

            // Admin
            // Publisher
            #endregion

            Assert.AreEqual(2, roles.Count);
            Assert.AreEqual("Admin", roles[0].Name);
            Assert.AreEqual("Publisher", roles[1].Name);
        }
コード例 #2
0
ファイル: Integers.cs プロジェクト: ALyman/Liquid.Json
 public void DeserializesUInt16()
 {
     var serializer = new JsonSerializer();
     Assert.AreEqual<UInt16>(0, serializer.Deserialize<UInt16>("0"));
     Assert.AreEqual<UInt16>(1, serializer.Deserialize<UInt16>("1"));
     Assert.AreEqual(UInt16.MaxValue, serializer.Deserialize<UInt16>("65535"));
 }
コード例 #3
0
ファイル: Integers.cs プロジェクト: ALyman/Liquid.Json
 public void DeserializesByte()
 {
     var serializer = new JsonSerializer();
     Assert.AreEqual<Byte>(0, serializer.Deserialize<Byte>("0"));
     Assert.AreEqual<Byte>(1, serializer.Deserialize<Byte>("1"));
     Assert.AreEqual(Byte.MaxValue, serializer.Deserialize<Byte>("255"));
 }
コード例 #4
0
ファイル: Integers.cs プロジェクト: ALyman/Liquid.Json
 public void DeserializesInt64()
 {
     var serializer = new JsonSerializer();
     Assert.AreEqual(0, serializer.Deserialize<Int64>("0"));
     Assert.AreEqual(1, serializer.Deserialize<Int64>("1"));
     Assert.AreEqual(-1, serializer.Deserialize<Int64>("-1"));
 }
コード例 #5
0
ファイル: Integers.cs プロジェクト: ALyman/Liquid.Json
 public void DeserializesSByte()
 {
     var serializer = new JsonSerializer();
     Assert.AreEqual<SByte>(0, serializer.Deserialize<SByte>("0"));
     Assert.AreEqual<SByte>(1, serializer.Deserialize<SByte>("1"));
     Assert.AreEqual<SByte>(-1, serializer.Deserialize<SByte>("-1"));
 }
コード例 #6
0
ファイル: Integers.cs プロジェクト: ALyman/Liquid.Json
 public void DeserializesUInt64()
 {
     var serializer = new JsonSerializer();
     Assert.AreEqual<UInt64>(0, serializer.Deserialize<UInt64>("0"));
     Assert.AreEqual<UInt64>(1, serializer.Deserialize<UInt64>("1"));
     Assert.AreEqual(UInt64.MaxValue, serializer.Deserialize<UInt64>("18446744073709551615"));
 }
コード例 #7
0
		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;
		}
コード例 #8
0
		public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
		{
			JObject o = JObject.Load(reader);
			var result = existingValue as AnalysisSettings ?? new AnalysisSettings();

			foreach (var rootProperty in o.Children<JProperty>())
			{
				if (rootProperty.Name.Equals("analyzer", StringComparison.InvariantCultureIgnoreCase))
				{
					result.Analyzers = serializer.Deserialize<IDictionary<string,AnalyzerBase>>(rootProperty.Value.CreateReader());
				}
				else if (rootProperty.Name.Equals("filter", StringComparison.InvariantCultureIgnoreCase))
				{
					result.TokenFilters = serializer.Deserialize<IDictionary<string, TokenFilterBase>>(rootProperty.Value.CreateReader());
				}
				else if (rootProperty.Name.Equals("tokenizer", StringComparison.InvariantCultureIgnoreCase))
				{
					result.Tokenizers = serializer.Deserialize<IDictionary<string, TokenizerBase>>(rootProperty.Value.CreateReader());
				}
				else if (rootProperty.Name.Equals("char_filter", StringComparison.InvariantCultureIgnoreCase))
				{
					result.CharFilters = serializer.Deserialize<IDictionary<string, CharFilterBase>>(rootProperty.Value.CreateReader());
				}
			}

			return result;
		}
コード例 #9
0
ファイル: Integers.cs プロジェクト: ALyman/Liquid.Json
 public void DeserializesUInt32()
 {
     var serializer = new JsonSerializer();
     Assert.AreEqual<UInt32>(0, serializer.Deserialize<UInt32>("0"));
     Assert.AreEqual<UInt32>(1, serializer.Deserialize<UInt32>("1"));
     Assert.AreEqual(UInt32.MaxValue, serializer.Deserialize<UInt32>("4294967295"));
 }
コード例 #10
0
ファイル: Reals.cs プロジェクト: ALyman/Liquid.Json
 public void DeserializesDouble()
 {
     var serializer = new JsonSerializer();
     Assert.AreEqual(0, serializer.Deserialize<Double>("0"));
     Assert.AreEqual(1, serializer.Deserialize<Double>("1"));
     Assert.AreEqual(-1, serializer.Deserialize<Double>("-1"));
     Assert.AreEqual(1.5, serializer.Deserialize<Double>("1.5"));
     Assert.AreEqual(-1.5, serializer.Deserialize<Double>("-1.5"));
 }
コード例 #11
0
ファイル: Reals.cs プロジェクト: ALyman/Liquid.Json
 public void DeserializesDecimal()
 {
     var serializer = new JsonSerializer();
     Assert.AreEqual(0m, serializer.Deserialize<Decimal>("0"));
     Assert.AreEqual(1m, serializer.Deserialize<Decimal>("1"));
     Assert.AreEqual(-1m, serializer.Deserialize<Decimal>("-1"));
     Assert.AreEqual(1.5m, serializer.Deserialize<Decimal>("1.5"));
     Assert.AreEqual(-1.5m, serializer.Deserialize<Decimal>("-1.5"));
 }
コード例 #12
0
 public void NullDeserialize()
 {
     var Serializer = new JsonSerializer();
     Assert.Equal(null, Serializer.Deserialize(typeof(object), null));
     Assert.Equal(null, Serializer.Deserialize(typeof(object), ""));
     Assert.Equal(null, Serializer.Deserialize(null, "ASDF"));
     Assert.Equal(null, Serializer.Deserialize(null, null));
     Assert.Equal(null, Serializer.Deserialize(null, ""));
 }
コード例 #13
0
ファイル: Reals.cs プロジェクト: ALyman/Liquid.Json
 public void DeserializesSingle()
 {
     var serializer = new JsonSerializer();
     Assert.AreEqual(0f, serializer.Deserialize<Single>("0"));
     Assert.AreEqual(1f, serializer.Deserialize<Single>("1"));
     Assert.AreEqual(-1f, serializer.Deserialize<Single>("-1"));
     Assert.AreEqual(1.5f, serializer.Deserialize<Single>("1.5"));
     Assert.AreEqual(-1.5f, serializer.Deserialize<Single>("-1.5"));
 }
コード例 #14
0
        public void JsonDeserializer_ShouldReturnCorrectResultWhenCorrectInput()
        {
            var serializer = new JsonSerializer();
            string input = "{\"Name\":\"Test\",\"Score\":65,\"Id\":\"1\"}";
            Player expResult = new Player { Name = "Test", Score = 65, Id = "1" };

            Assert.AreEqual(expResult.Name, serializer.Deserialize<Player>(input).Name);
            Assert.AreEqual(expResult.Score, serializer.Deserialize<Player>(input).Score);
            Assert.AreEqual(expResult.Id, serializer.Deserialize<Player>(input).Id);
        }
コード例 #15
0
 public void Deserialize()
 {
     var Serializer = new JsonSerializer();
     dynamic Object = (TestObject)Serializer.Deserialize(typeof(TestObject), "{\"A\":5,\"B\":\"ASDF\"}");
     Assert.Equal(5, Object.A);
     Assert.Equal("ASDF", Object.B);
     Object = (ExpandoObject)Serializer.Deserialize(typeof(ExpandoObject), "{\"A\":5,\"B\":\"ASDF\"}");
     Assert.Equal(5, Object.A);
     Assert.Equal("ASDF", Object.B);
     Object = (Dynamo)Serializer.Deserialize(typeof(Dynamo), "{\"A\":5,\"B\":\"ASDF\"}");
     Assert.Equal(5, Object.A);
     Assert.Equal("ASDF", Object.B);
 }
コード例 #16
0
    /// <summary>
    /// Reads the JSON representation of the object.
    /// </summary>
    /// <param name="reader">The <see cref="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)
    {
      IList<Type> genericArguments = objectType.GetGenericArguments();
      Type keyType = genericArguments[0];
      Type valueType = genericArguments[1];

      reader.Read();
      reader.Read();
      object key = serializer.Deserialize(reader, keyType);
      reader.Read();
      reader.Read();
      object value = serializer.Deserialize(reader, valueType);
      reader.Read();

      return ReflectionUtils.CreateInstance(objectType, key, value);
    }
コード例 #17
0
ファイル: Arrays.cs プロジェクト: ALyman/Liquid.Json
 public void DeserializesEmptyEnumerable()
 {
     var serializer = new JsonSerializer();
     var result = serializer.Deserialize<IEnumerable<int>>("[]");
     Assert.IsNotNull(result);
     Assert.AreEqual(0, result.Count());
 }
コード例 #18
0
ファイル: Arrays.cs プロジェクト: ALyman/Liquid.Json
 public void DeserializesEmptyList()
 {
     var serializer = new JsonSerializer();
     var result = serializer.Deserialize<IList<int>>("[]");
     Assert.IsNotNull(result);
     Assert.AreEqual(0, result.Count);
 }
コード例 #19
0
        public void DeserializeNestedUnhandled()
        {
            List<string> errors = new List<string>();

              string json = @"[[""kjhkjhkjhkjh""]]";

              try
              {
            JsonSerializer serializer = new JsonSerializer();
            serializer.Error += delegate(object sender, ErrorEventArgs args)
              {
            // only log an error once
            if (args.CurrentObject == args.ErrorContext.OriginalObject)
              errors.Add(args.ErrorContext.Error.Message);
              };

            serializer.Deserialize(new StringReader(json), typeof(List<List<DateTime>>));
              }
              catch (Exception ex)
              {
            Console.WriteLine(ex.Message);
              }

              Assert.AreEqual(1, errors.Count);
              Assert.AreEqual(@"Error converting value ""kjhkjhkjhkjh"" to type 'System.DateTime'.", errors[0]);
        }
コード例 #20
0
        public void testJsonDeserializingAnalyticServiceStatus()
        {
            String source =
                    "{" +
                        "\"service_status\":\"online\"," +
                        "\"api_version\":\"2.0\"," +
                        "\"service_version\":\"1.0.2.63\"," +
                        "\"supported_encoding\":\"UTF-8\"," +
                        "\"supported_compression\":\"gzip\"," +
                        "\"supported_languages\":[" +
                                "\"English\"," +
                                "\"French\"" +
                        "]" +
                    "}";

            ISerializer serializer = new JsonSerializer();
            Status status = serializer.Deserialize<Status>(source);
            Assert.AreEqual("online", status.Service);
            Assert.AreEqual("2.0", status.ApiVersion);
            Assert.AreEqual("1.0.2.63", status.ServiceVersion);
            Assert.AreEqual("UTF-8", status.SupportedEncoding);
            Assert.AreEqual("gzip", status.SupportedCompression);
            Assert.AreEqual(2, status.SupportedLanguages.Count);
            Assert.AreEqual("English", status.SupportedLanguages[0]);
            Assert.AreEqual("French", status.SupportedLanguages[1]);
        }
コード例 #21
0
ファイル: Arrays.cs プロジェクト: ALyman/Liquid.Json
 public void DeserializesEmptyArray()
 {
     var serializer = new JsonSerializer();
     var result = serializer.Deserialize<int[]>("[]");
     Assert.IsNotNull(result);
     Assert.AreEqual(0, result.Length);
 }
コード例 #22
0
		public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
		{
			var collection = new NameValueCollection();

			while (reader.Read())
			{
				if (reader.TokenType == JsonToken.EndObject)
					break;

				var key = (string)reader.Value;

				if (reader.Read() == false)
					throw new InvalidOperationException("Expected PropertyName, got " + reader.TokenType);

				if (reader.TokenType == JsonToken.StartArray)
				{
					var values = serializer.Deserialize<string[]>(reader);
					foreach (var value in values)
					{
						collection.Add(key, value);
					}
				}
				else
				{
					collection.Add(key, reader.Value.ToString());
				}
			}

			return collection;
		}
コード例 #23
0
 public void Deserialize()
 {
     var Serializer = new JsonSerializer();
     var Object = (TestObject)Serializer.Deserialize(typeof(TestObject), "{\"A\":5,\"B\":\"ASDF\"}");
     Assert.Equal(5, Object.A);
     Assert.Equal("ASDF", Object.B);
 }
コード例 #24
0
ファイル: Other.cs プロジェクト: ALyman/Liquid.Json
        public void Date()
        {
            var serializer = new JsonSerializer();
            DateTime EPOCH = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);

            Action<DateTime, string> CheckDate = (date, json) => {
                var result = serializer.Deserialize<DateTime>(json);
                var diff = date.Subtract(result);
                Assert.IsTrue(diff.TotalSeconds < 1, string.Format("Dates do not match: <{0}> != <{1}>, difference: {2}, json: <{3}>", date, result, diff.TotalSeconds, json));
            };

            Action<DateTime> TestDate = (source) => {
                CheckDate(source, string.Format("new Date({0})", (long)(source - EPOCH).TotalMilliseconds));
                CheckDate(source, string.Format("new Date(\"{0}\")", source.ToString("MMMM d, yyyy HH:mm:ss zzz")));
                CheckDate(source, string.Format("new Date({0}, {1}, {2}, {3}, {4}, {5}, {6})", source.Year, source.Month, source.Day, source.Hour, source.Minute, source.Second, source.Millisecond));
            };

            TestDate(new DateTime(1970, 1, 2, 0, 0, 0, DateTimeKind.Utc));
            TestDate(new DateTime(1970, 1, 2, 4, 0, 0, DateTimeKind.Utc));
            TestDate(new DateTime(1970, 1, 2, 14, 0, 0, DateTimeKind.Utc));
            TestDate(DateTime.Now);
            TestDate(DateTime.UtcNow);

            CheckDate(new DateTime(1970, 1, 2, 4, 1, 2), "new Date(1970, 1, 2, 14, 0, 0)");
            CheckDate(new DateTime(1970, 1, 2, 4, 1, 0), "new Date(1970, 1, 2, 14, 0)");
            CheckDate(new DateTime(1970, 1, 2, 4, 0, 0), "new Date(1970, 1, 2, 14)");
            CheckDate(new DateTime(1970, 1, 2, 0, 0, 0), "new Date(1970, 1, 2)");
        }
コード例 #25
0
		public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
		{
			JObject o = JObject.Load(reader);
			var result = existingValue as Dictionary<string, CharFilterBase> ?? new Dictionary<string, CharFilterBase>();

			foreach (var childProperty in o.Children<JProperty>())
			{
				var propertyName = childProperty.Name;
				var typeProperty = ((JObject)childProperty.Value).Property("type");
				typeProperty.Remove();

				var typePropertyValue = typeProperty.Value.ToString().Replace("_", string.Empty);

				CharFilterBase item;
				var itemType = Type.GetType("Nest." + typePropertyValue + "CharFilter", false, true);
				if (itemType != null)
				{
					item = serializer.Deserialize(childProperty.Value.CreateReader(), itemType) as CharFilterBase;
				}
				else
				{
					continue;
				}

				result[propertyName] = item;
			}
			return result;
		}
コード例 #26
0
		/// <summary>
		/// Reads the JSON representation of the object.
		/// </summary>
		/// <param name="reader">The <see cref="T:Raven.Imports.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)
		{
		    var token = RavenJToken.ReadFrom(reader);
		    var val = token as RavenJValue;
		    if(val != null)
		        return val.Value;
		    var array = token as RavenJArray;
			if (array != null)
			{
				var dynamicJsonObject = new DynamicJsonObject(new RavenJObject());
				return new DynamicList(array.Select(dynamicJsonObject.TransformToValue).ToArray());
			}

			var typeName = token.Value<string>("$type");
			if(typeName != null)
			{
				var type = Type.GetType(typeName, false);
				if(type != null)
				{
					return serializer.Deserialize(new RavenJTokenReader(token), type);
				}
			}

		    return new DynamicJsonObject((RavenJObject)((RavenJObject)token).CloneToken());
		}
コード例 #27
0
ファイル: Dictionaries.cs プロジェクト: ALyman/Liquid.Json
 public void DeserializesEmptyDictionary()
 {
     var serializer = new JsonSerializer();
     var result = serializer.Deserialize<IDictionary<string, int>>("{}");
     Assert.IsNotNull(result);
     Assert.AreEqual(0, result.Count);
 }
コード例 #28
0
ファイル: MainPage.xaml.cs プロジェクト: Qwin/SimplyMobile
        // Constructor
        public MainPage()
        {
            InitializeComponent();

            this.webHybrid = new WebHybrid(this.webView, new JsonSerializer());

            SaveFilesInHTMLFolderToIsoStore();
            this.webView.Navigate(new Uri("HTML/home.html", UriKind.Relative));

            //var fi = new FileInfo(@"./Assets/home.html");

            //using (var streamReader = new StreamReader(fi.FullName))
            //{
            //    this.webView.NavigateToString(streamReader.ReadToEnd());
            //}

            this.webHybrid.RegisterCallback("test", s =>
                {
                    System.Diagnostics.Debug.WriteLine(s);
                    var serializer = new JsonSerializer();
                    var m = serializer.Deserialize<ChartViewModel>(s);
                    System.Diagnostics.Debug.WriteLine(m);
                });

            this.webHybrid.RegisterCallback("dataCallback", s => System.Diagnostics.Debug.WriteLine(s));
        }
コード例 #29
0
        /// <summary>
        /// Reads the JSON representation of the object.
        /// </summary>
        /// <param name="reader">The <see cref="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)
        {
            bool isNullable = ReflectionUtils.IsNullableType(objectType);

            Type t = (isNullable)
                         ? Nullable.GetUnderlyingType(objectType)
                         : objectType;

            ReflectionObject reflectionObject = ReflectionObjectPerType.Get(t);

            if (reader.TokenType == JsonToken.Null)
            {
                if (!isNullable)
                    throw JsonSerializationException.Create(reader, "Cannot convert null value to Matrix4x4.");

                return null;
            }

            object[] values = new object[PropNames.Length];

            ReadAndAssert(reader);

            while (reader.TokenType == JsonToken.PropertyName)
            {
                string propertyName = reader.Value.ToString();

                var index = Array.IndexOf(PropNames, propertyName);
                if (index != -1)
                {
                    var name = PropNames[index];
                    ReadAndAssert(reader);
                    values[index] = serializer.Deserialize(reader, reflectionObject.GetType(name));
                }
                else
                {
                    reader.Skip();
                }

                ReadAndAssert(reader);
            }

            var matrix = (Matrix4x4)reflectionObject.Creator();
            matrix.m00 = (float)values[0];
            matrix.m01 = (float)values[1];
            matrix.m02 = (float)values[2];
            matrix.m03 = (float)values[3];
            matrix.m10 = (float)values[4];
            matrix.m11 = (float)values[5];
            matrix.m12 = (float)values[6];
            matrix.m13 = (float)values[7];
            matrix.m20 = (float)values[8];
            matrix.m21 = (float)values[9];
            matrix.m22 = (float)values[10];
            matrix.m23 = (float)values[11];
            matrix.m30 = (float)values[12];
            matrix.m31 = (float)values[13];
            matrix.m32 = (float)values[14];
            matrix.m33 = (float)values[15];
            return matrix;
        }
コード例 #30
0
ファイル: JsonSerializerTest.cs プロジェクト: asipe/Nucs
 public void TestBasicSerialization()
 {
     var serializer = new JsonSerializer();
       var expected = CA<PlanDto>();
       var json = serializer.Serialize(expected);
       Compare(serializer.Deserialize<PlanDto>(json), expected);
 }
コード例 #31
0
        /// <inheritdoc/>
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            if (objectType == typeof(bool))
            {
                return(Convert.ToBoolean(reader?.Value, CultureInfo.InvariantCulture));
            }

            return(serializer?.Deserialize(reader, objectType));
        }
コード例 #32
0
        public override object ReadJson(JsonReader reader, Type t, object existingValue, JsonSerializer serializer)
        {
            if (reader?.TokenType == JsonToken.Null)
            {
                return(null);
            }

            var value = serializer?.Deserialize <string>(reader);

            return(value switch
            {
                "choice" => QuestionTypeEnum.Choice,
                "numeric" => QuestionTypeEnum.Numeric,
                _ => throw new Exception(Exceptions.CannotUnmarshalTypeEnum)
            });
コード例 #33
0
        internal static async Task SaveAllVideoMetadata(string jsonPath, Action <string>?log = null, params string[] directories)
        {
            log ??= TraceLog;
            Dictionary <string, Dictionary <string, VideoMetadata> > existingMetadata = File.Exists(jsonPath)
                ? JsonSerializer.Deserialize <Dictionary <string, Dictionary <string, VideoMetadata> > >(await File.ReadAllTextAsync(jsonPath))
                                                                                        ?? throw new InvalidOperationException(jsonPath)
                : new();

            existingMetadata
            .Values
            .ForEach(group => group
                     .Keys
                     .ToArray()
                     .Where(video => !File.Exists(Path.IsPathRooted(video) ? video : Path.Combine(Path.GetDirectoryName(jsonPath) ?? string.Empty, video)))
                     .ForEach(video => group.Remove(video)));

            Dictionary <string, string> existingVideos = existingMetadata
                                                         .Values
                                                         .SelectMany(group => group.Keys)
                                                         .ToDictionary(video => video, _ => string.Empty);

            Dictionary <string, Dictionary <string, VideoMetadata> > allVideoMetadata = directories
                                                                                        .SelectMany(directory => Directory.GetFiles(directory, JsonMetadataSearchPattern, SearchOption.AllDirectories))
                                                                                        .AsParallel()
                                                                                        .WithDegreeOfParallelism(IOMaxDegreeOfParallelism)
                                                                                        .SelectMany(movieJson =>
            {
                string relativePath = Path.GetDirectoryName(jsonPath) ?? string.Empty;
                Imdb.TryLoad(movieJson, out ImdbMetadata? imdbMetadata);
                return(Directory
                       .GetFiles(Path.GetDirectoryName(movieJson) ?? string.Empty, PathHelper.AllSearchPattern, SearchOption.TopDirectoryOnly)
                       .Where(video => video.IsCommonVideo() && !existingVideos.ContainsKey(Path.GetRelativePath(relativePath, video)))
                       .Select(video =>
                {
                    if (!TryGetVideoMetadata(video, out VideoMetadata? videoMetadata, imdbMetadata, relativePath))
                    {
                        log($"!Fail: {video}");
                    }

                    return videoMetadata;
                })
                       .NotNull());
            })
                                                                                        .ToLookup(videoMetadata => videoMetadata.Imdb?.ImdbId ?? string.Empty, metadata => metadata)
                                                                                        .ToDictionary(group => group.Key, group => group.ToDictionary(videoMetadata => videoMetadata.File, videoMetadata => videoMetadata));

            allVideoMetadata.ForEach(
                group =>
            {
                if (!existingMetadata.ContainsKey(group.Key))
                {
                    existingMetadata[group.Key] = new();
                }

                group.Value.ForEach(pair => existingMetadata[group.Key][pair.Key] = pair.Value);
            });

            existingMetadata
            .Keys
            .ToArray()
            .Where(imdbId => !existingMetadata[imdbId].Any())
            .ForEach(imdbId => existingMetadata.Remove(imdbId));

            string mergedVideoMetadataJson = JsonSerializer.Serialize(existingMetadata, new() { WriteIndented = true });
            await File.WriteAllTextAsync(jsonPath, mergedVideoMetadataJson);
        }
コード例 #34
0
        public static void UpdateVersions(bool saveFile, bool readFromFile)
        {
            if (saveFile)
            {
                if (File.Exists(VersionsFilePath))
                {
                    JsonSerializer js = new JsonSerializer();
                    js.NullValueHandling = NullValueHandling.Ignore;
                    using (StreamWriter sw = new StreamWriter(VersionsFilePath))
                        using (JsonWriter jw = new JsonTextWriter(sw))
                        {
                            js.Serialize(jw, Versions);
                        }
                }
                else
                {
                    if (!Directory.Exists(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "/ForgeModBuilder"))
                    {
                        Directory.CreateDirectory(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "/ForgeModBuilder");
                    }
                    File.Create(VersionsFilePath).Dispose();
                    UpdateVersions(saveFile, readFromFile);
                }
            }
            if (readFromFile)
            {
                if (File.Exists(VersionsFilePath))
                {
                    JsonSerializer js = new JsonSerializer();
                    js.NullValueHandling = NullValueHandling.Ignore;
                    using (StreamReader sr = new StreamReader(VersionsFilePath))
                        using (JsonReader jr = new JsonTextReader(sr))
                        {
                            Versions = js.Deserialize <Dictionary <string, List <string> > >(jr);
                        }
                    if (Versions == null)
                    {
                        Versions = new Dictionary <string, List <string> >();
                    }
                    if (Versions.Keys.Count > 0)
                    {
                        Version latest = new Version(Versions.Keys.First());
                        LatestMinecraftVersion = Versions.Keys.First();
                        Version current;
                        foreach (string version in Versions.Keys)
                        {
                            current = new Version(version.Contains("_") ? version.Substring(0, version.IndexOf("_") - 1) : version);
                            if (latest.CompareTo(current) < 0)
                            {
                                LatestMinecraftVersion = version;
                                latest = new Version(LatestMinecraftVersion);
                            }
                        }
                        Console.WriteLine("Latest version: " + LatestMinecraftVersion);
                    }
                }
                else
                {
                    if (!Directory.Exists(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "/ForgeModBuilder"))
                    {
                        Directory.CreateDirectory(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "/ForgeModBuilder");
                    }
                    File.Create(VersionsFilePath).Dispose();
                    UpdateVersions(saveFile, readFromFile);
                }
            }
            Program.INSTANCE.SelectVersionsToCheckMenuItem.DropDownItems.Clear();
            Dictionary <string, bool> checkVersions = new Dictionary <string, bool>();

            if (Program.INSTANCE.Options.ContainsKey("sync_versions"))
            {
                checkVersions = (Dictionary <string, bool>)Program.INSTANCE.Options["sync_versions"];
            }
            foreach (string mcversion in Versions.Keys)
            {
                ToolStripMenuItem menuItem = new ToolStripMenuItem(mcversion);
                if (checkVersions.Count != 0 && checkVersions.ContainsKey(mcversion))
                {
                    menuItem.Checked = checkVersions[mcversion];
                }
                menuItem.Click += (sender, args) => {
                    menuItem.Checked = !menuItem.Checked;
                };
                Program.INSTANCE.SelectVersionsToCheckMenuItem.DropDownItems.Add(menuItem);
            }
        }
コード例 #35
0
        public async Task <Social> GetAsync(string culture)
        {
            var expiration = DateTime.Now.AddHours(CacheInHours).Ticks;

            int?headerId = await _cache.GetIntFromCacheAsync(CacheKey.SocialHeader);

            if (!headerId.HasValue)
            {
                var headerIdRecord = await _socialHeaderRepository
                                     .GetByDateAsync(_dateTimeProvider.Now);

                if (headerIdRecord == null)
                {
                    return(null);
                }

                if (headerIdRecord.NextStartDate.HasValue &&
                    headerIdRecord.NextStartDate.Value != default)
                {
                    expiration = Math.Min(expiration,
                                          headerIdRecord.NextStartDate.Value.Ticks);
                }

                await _cache.SaveToCacheAsync(CacheKey.SocialHeader,
                                              headerIdRecord.Id,
                                              TimeSpan.FromTicks(expiration));

                headerId = headerIdRecord.Id;
            }

            if (!headerId.HasValue)
            {
                return(null);
            }

            var languageId = await _languageService.GetLanguageIdAsync(culture);

            Social social = null;

            var cacheKey = GetCacheKey(CacheKey.Social, headerId.Value, languageId);

            var socialCache = await _cache.GetStringFromCache(cacheKey);

            if (!string.IsNullOrEmpty(socialCache))
            {
                try
                {
                    social = JsonSerializer.Deserialize <Social>(socialCache);
                }
                catch (JsonException jex)
                {
                    _logger.LogError("Unable to deserialize social object: {ErrorMessage}",
                                     jex.Message);
                }
            }

            if (social == null)
            {
                social = await _socialRepository.GetByHeaderLanguageAsync(headerId.Value, languageId);

                await _cache.SaveToCacheAsync(cacheKey,
                                              JsonSerializer.Serialize(social),
                                              TimeSpan.FromTicks(expiration));
            }

            return(social);
        }
コード例 #36
0
        public async Task PopulateModsList()
        {
            try
            {
                var resp = await HttpClient.GetAsync(Utils.Constants.BeatModsAPIUrl + Utils.Constants.BeatModsModsOptions + "&gameVersion=" + MainWindow.GameVersion);

                var body = await resp.Content.ReadAsStringAsync();

                ModsList = JsonSerializer.Deserialize <Mod[]>(body);
            }
            catch (Exception e)
            {
                System.Windows.MessageBox.Show($"{FindResource("Mods:LoadFailed")}.\n\n" + e);
                return;
            }

            foreach (Mod mod in ModsList)
            {
                bool preSelected = mod.required;
                if (DefaultMods.Contains(mod.name) || (App.SaveModSelection && App.SavedMods.Contains(mod.name)))
                {
                    preSelected = true;
                    if (!App.SavedMods.Contains(mod.name))
                    {
                        App.SavedMods.Add(mod.name);
                    }
                }

                RegisterDependencies(mod);

                ModListItem ListItem = new ModListItem()
                {
                    IsSelected     = preSelected,
                    IsEnabled      = !mod.required,
                    ModName        = mod.name,
                    ModVersion     = mod.version,
                    ModDescription = mod.description.Replace("\r\n", " ").Replace("\n", " "),
                    ModInfo        = mod,
                    Category       = mod.category
                };

                foreach (Promotion promo in Promotions.List)
                {
                    if (promo.Active && mod.name == promo.ModName)
                    {
                        ListItem.PromotionTexts          = new string[promo.Links.Count];
                        ListItem.PromotionLinks          = new string[promo.Links.Count];
                        ListItem.PromotionTextAfterLinks = new string[promo.Links.Count];

                        for (int i = 0; i < promo.Links.Count; ++i)
                        {
                            PromotionLink link = promo.Links[i];
                            ListItem.PromotionTexts[i]          = link.Text;
                            ListItem.PromotionLinks[i]          = link.Link;
                            ListItem.PromotionTextAfterLinks[i] = link.TextAfterLink;
                        }
                    }
                }

                foreach (Mod installedMod in InstalledMods)
                {
                    if (mod.name == installedMod.name)
                    {
                        ListItem.InstalledModInfo = installedMod;
                        ListItem.IsInstalled      = true;
                        ListItem.InstalledVersion = installedMod.version;
                        break;
                    }
                }

                mod.ListItem = ListItem;

                ModList.Add(ListItem);
            }

            foreach (Mod mod in ModsList)
            {
                ResolveDependencies(mod);
            }
        }
コード例 #37
0
 public T Deserialize(string value)
 {
     return(JsonSerializer.Deserialize <T>(value));
 }
コード例 #38
0
        public void ProcessRequest(HttpContext context)
        {
            try
            {
                string       Code   = context.Request.Form["customCode"];
                WebClient    web    = new WebClient();
                StreamReader reader = null;
                //获取公司服务地址
                string getCompanyAddress1 = System.Web.Configuration.WebConfigurationManager.AppSettings["getCompanyAddress1"].ToString();
                string getCompanyAddress2 = System.Web.Configuration.WebConfigurationManager.AppSettings["getCompanyAddress2"].ToString();
                web = new WebClient();
                getCompanyAddress1 = getCompanyAddress1 + Code;
                getCompanyAddress2 = getCompanyAddress2 + Code;
                //远程获取公司信息
                System.IO.Stream getCompany1 = web.OpenRead(getCompanyAddress1);
                System.IO.Stream getCompany2 = web.OpenRead(getCompanyAddress2);

                reader = new StreamReader(getCompany1);
                string strCompany1 = reader.ReadToEnd();
                getCompany1.Close();

                reader = new StreamReader(getCompany2);
                string strCompany2 = reader.ReadToEnd();
                getCompany2.Close();

                reader.Dispose();

                if (!strCompany1.Equals(""))
                {
                    try
                    {
                        //转换为公司对像
                        JsonSerializer       serializer = new JsonSerializer();
                        StringReader         sr         = new StringReader(strCompany1);
                        PageBase.CompanyData obj        = serializer.Deserialize <PageBase.CompanyData>(new JsonTextReader(sr));
                        context.Response.Write(JsonConvert.SerializeObject(new Data("", obj.FULL_NAME)));
                    }
                    catch (Exception ex)
                    {
                        context.Response.Write(JsonConvert.SerializeObject(new Data("转换企业对像失败:" + strCompany1 + "|" + ex.Message.ToString(), "")));
                    }
                }
                else if (!strCompany2.Equals(""))
                {
                    try
                    {
                        //转换为公司对像
                        JsonSerializer       serializer = new JsonSerializer();
                        StringReader         sr         = new StringReader(strCompany2);
                        PageBase.CompanyData obj        = serializer.Deserialize <PageBase.CompanyData>(new JsonTextReader(sr));
                        context.Response.Write(JsonConvert.SerializeObject(new Data("", obj.FULL_NAME)));
                    }
                    catch (Exception ex)
                    {
                        context.Response.Write(JsonConvert.SerializeObject(new Data("转换企业对像失败:" + strCompany2 + "|" + ex.Message.ToString(), "")));
                    }
                }
                else
                {
                    context.Response.Write(JsonConvert.SerializeObject(new Data("获取公司信息失败!", "")));
                }
            }
            catch (Exception ex)
            {
                context.Response.Write(JsonConvert.SerializeObject(new Data(ex.Message.ToString(), "")));
            }
        }
コード例 #39
0
        internal static VMwareClusterData DeserializeVMwareClusterData(JsonElement element)
        {
            Optional <ExtendedLocation>  extendedLocation = default;
            Optional <string>            kind             = default;
            IDictionary <string, string> tags             = default;
            AzureLocation      location        = default;
            ResourceIdentifier id              = default;
            string             name            = default;
            ResourceType       type            = default;
            SystemData         systemData      = default;
            Optional <string>  uuid            = default;
            Optional <string>  vCenterId       = default;
            Optional <string>  moRefId         = default;
            Optional <string>  inventoryItemId = default;
            Optional <string>  moName          = default;
            Optional <IReadOnlyList <ResourceStatus> > statuses = default;
            Optional <string> customResourceName            = default;
            Optional <IReadOnlyList <string> > datastoreIds = default;
            Optional <IReadOnlyList <string> > networkIds   = default;
            Optional <string> provisioningState             = default;

            foreach (var property in element.EnumerateObject())
            {
                if (property.NameEquals("extendedLocation"))
                {
                    if (property.Value.ValueKind == JsonValueKind.Null)
                    {
                        property.ThrowNonNullablePropertyIsNull();
                        continue;
                    }
                    extendedLocation = ExtendedLocation.DeserializeExtendedLocation(property.Value);
                    continue;
                }
                if (property.NameEquals("kind"))
                {
                    kind = property.Value.GetString();
                    continue;
                }
                if (property.NameEquals("tags"))
                {
                    Dictionary <string, string> dictionary = new Dictionary <string, string>();
                    foreach (var property0 in property.Value.EnumerateObject())
                    {
                        dictionary.Add(property0.Name, property0.Value.GetString());
                    }
                    tags = dictionary;
                    continue;
                }
                if (property.NameEquals("location"))
                {
                    location = property.Value.GetString();
                    continue;
                }
                if (property.NameEquals("id"))
                {
                    id = new ResourceIdentifier(property.Value.GetString());
                    continue;
                }
                if (property.NameEquals("name"))
                {
                    name = property.Value.GetString();
                    continue;
                }
                if (property.NameEquals("type"))
                {
                    type = property.Value.GetString();
                    continue;
                }
                if (property.NameEquals("systemData"))
                {
                    systemData = JsonSerializer.Deserialize <SystemData>(property.Value.ToString());
                    continue;
                }
                if (property.NameEquals("properties"))
                {
                    if (property.Value.ValueKind == JsonValueKind.Null)
                    {
                        property.ThrowNonNullablePropertyIsNull();
                        continue;
                    }
                    foreach (var property0 in property.Value.EnumerateObject())
                    {
                        if (property0.NameEquals("uuid"))
                        {
                            uuid = property0.Value.GetString();
                            continue;
                        }
                        if (property0.NameEquals("vCenterId"))
                        {
                            vCenterId = property0.Value.GetString();
                            continue;
                        }
                        if (property0.NameEquals("moRefId"))
                        {
                            moRefId = property0.Value.GetString();
                            continue;
                        }
                        if (property0.NameEquals("inventoryItemId"))
                        {
                            inventoryItemId = property0.Value.GetString();
                            continue;
                        }
                        if (property0.NameEquals("moName"))
                        {
                            moName = property0.Value.GetString();
                            continue;
                        }
                        if (property0.NameEquals("statuses"))
                        {
                            if (property0.Value.ValueKind == JsonValueKind.Null)
                            {
                                property0.ThrowNonNullablePropertyIsNull();
                                continue;
                            }
                            List <ResourceStatus> array = new List <ResourceStatus>();
                            foreach (var item in property0.Value.EnumerateArray())
                            {
                                array.Add(ResourceStatus.DeserializeResourceStatus(item));
                            }
                            statuses = array;
                            continue;
                        }
                        if (property0.NameEquals("customResourceName"))
                        {
                            customResourceName = property0.Value.GetString();
                            continue;
                        }
                        if (property0.NameEquals("datastoreIds"))
                        {
                            if (property0.Value.ValueKind == JsonValueKind.Null)
                            {
                                property0.ThrowNonNullablePropertyIsNull();
                                continue;
                            }
                            List <string> array = new List <string>();
                            foreach (var item in property0.Value.EnumerateArray())
                            {
                                array.Add(item.GetString());
                            }
                            datastoreIds = array;
                            continue;
                        }
                        if (property0.NameEquals("networkIds"))
                        {
                            if (property0.Value.ValueKind == JsonValueKind.Null)
                            {
                                property0.ThrowNonNullablePropertyIsNull();
                                continue;
                            }
                            List <string> array = new List <string>();
                            foreach (var item in property0.Value.EnumerateArray())
                            {
                                array.Add(item.GetString());
                            }
                            networkIds = array;
                            continue;
                        }
                        if (property0.NameEquals("provisioningState"))
                        {
                            provisioningState = property0.Value.GetString();
                            continue;
                        }
                    }
                    continue;
                }
            }
            return(new VMwareClusterData(id, name, type, systemData, tags, location, extendedLocation.Value, kind.Value, uuid.Value, vCenterId.Value, moRefId.Value, inventoryItemId.Value, moName.Value, Optional.ToList(statuses), customResourceName.Value, Optional.ToList(datastoreIds), Optional.ToList(networkIds), provisioningState.Value));
        }
コード例 #40
0
 /// <summary>
 /// This is used for MultiCall response resolution
 /// <returns>Type</returns>
 /// </summary>
 override public Response ReadResponse(ref Utf8JsonReader reader, JsonSerializerOptions options)
 {
     return(JsonSerializer.Deserialize <OrderAuthorizeResponse>(ref reader, options));
 }
コード例 #41
0
 public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
 {
     return(serializer.Deserialize <T>(reader));
 }
コード例 #42
0
        public async Task <T> ExecuteRestMethodWithJsonSerializerOptions <T>(string url, JsonSerializerOptions options = null)
        {
            string rawResultData = await ExecuteRestMethod(url);

            return(JsonSerializer.Deserialize <T>(rawResultData, options == null ? _jsonSerializerOptions : options));
        }
コード例 #43
0
        public async Task <CustomerBasket> GetBasketAsync(string basketId)
        {
            var data = await _database.StringGetAsync(basketId);

            return(data.IsNullOrEmpty ? null : JsonSerializer.Deserialize <CustomerBasket>(data));
        }