Example #1
0
        public static void SerializePerformanceTesting()
        {
            var options = new System.Text.Json.JsonSerializerOptions {
                WriteIndented = true
            };

            List <Team> teams = new List <Team>();

            for (int i = 0; i < 1000000; i++)
            {
                teams.Add(WorkWithSerialize.MakeOneTeam());
            }

            System.Diagnostics.Stopwatch watch = new System.Diagnostics.Stopwatch();
            watch.Start();
            var newtonsoft = Newtonsoft.Json.JsonConvert.SerializeObject(teams);

            Console.WriteLine($"Serialize Newtonsoft {watch.ElapsedMilliseconds} ms");

            watch.Restart();
            Newtonsoft.Json.JsonConvert.SerializeObject(teams, Newtonsoft.Json.Formatting.Indented);
            Console.WriteLine($"Serialize Newtonsoft {watch.ElapsedMilliseconds} ms (pretty json)");

            watch.Restart();
            var netCore = System.Text.Json.JsonSerializer.Serialize(teams);

            Console.WriteLine($"Serialize System.Text.Json {watch.ElapsedMilliseconds} ms");

            watch.Restart();
            System.Text.Json.JsonSerializer.Serialize(teams, options);
            Console.WriteLine($"Serialize System.Text.Json {watch.ElapsedMilliseconds} ms (pretty json)");

            watch.Restart();
            List <Team> teamsNetCore = System.Text.Json.JsonSerializer.Deserialize <List <Team> >(netCore);

            Console.WriteLine($"Deserialize System.Text.Json {watch.ElapsedMilliseconds} ms");

            watch.Restart();
            List <Team> teamsNewtonsoft = Newtonsoft.Json.JsonConvert.DeserializeObject <List <Team> >(newtonsoft);

            Console.WriteLine($"Deserialize Newtonsoft {watch.ElapsedMilliseconds} ms");

            watch.Stop();
        }
        private void InitPhotos()
        {
            photoDs = new PhotosDataSource {
                HttpFactory = HttpFactory
            };
            photoOp = new GridOptions
            {
                Datasource             = photoDs,
                EnablePagination       = true,
                PaginationPageSize     = 20,
                SuppressRowDeselection = true,
                RowModelType           = RowModelType.Infinite,
                RowSelection           = RowSelection.Multiple,
                SuppressCellSelection  = true,
                EnableBrowserTooltips  = true
            };
            photoEv = new GridEvents
            {
                SelectionChanged = (Action <RowNode[]>)(nodes =>
                {
                    Console.WriteLine("Photo Selected: " + (nodes?.Length == 0
                        ? "none" : string.Join(",", nodes.Select(n => n.Id))));

                    if ((nodes?.Length ?? 0) == 0)
                    {
                        thumbnails = null;
                    }
                    else
                    {
                        var opts = new System.Text.Json.JsonSerializerOptions
                        {
                            PropertyNameCaseInsensitive = true,
                        };
                        var photos = System.Text.Json.JsonSerializer.Deserialize <Photo[]>(
                            System.Text.Json.JsonSerializer.Serialize(
                                nodes.Select(n => n.Data), opts), opts);
                        thumbnails = photos.Select(p => p.ThumbnailUrl);
                    }
                    StateHasChanged();
                }),
            };
        }
Example #3
0
        //-------------------------------------------------------------------------------
        public void Save()
        {
            var options = new System.Text.Json.JsonSerializerOptions
            {
                // Pretty-print so it can be edited easily by humies.
                WriteIndented = true,
            };
            string text = System.Text.Json.JsonSerializer.Serialize(fields, options);

            ignoreFileChangesAt = DateTime.Now;
            try
            {
                File.WriteAllText(SettingsFilePath, text);
            }
            catch (IOException)
            {
                // Couldn't save settings. Probably should tell someone about this.
                // Oh well...
            }
        }
Example #4
0
        public bool guardarUsuario(Usuario usuario)
        {
            List <Usuario> usuarios;

            String jsonString = File.ReadAllText(this.path);

            usuarios = System.Text.Json.JsonSerializer.Deserialize <List <Usuario> >(jsonString);

            usuarios.Add(usuario);

            var options = new System.Text.Json.JsonSerializerOptions
            {
                WriteIndented = true
            };

            jsonString = System.Text.Json.JsonSerializer.Serialize(usuarios, options);

            File.WriteAllText(path, jsonString);

            return(true);
        }
        public void RSAParametersJsonSerialization()
        {
            // Arrange
            CryptographyFactory f = new CryptographyFactory();

            System.Security.Cryptography.RSAParameters rsaParameters;
            using (System.Security.Cryptography.RSACryptoServiceProvider csp = new System.Security.Cryptography.RSACryptoServiceProvider())
            {
                rsaParameters = csp.ExportParameters(true);
            }

            // Act
            System.Text.Json.JsonSerializerOptions opts = new System.Text.Json.JsonSerializerOptions();
            opts.WriteIndented = true;
            string json = System.Text.Json.JsonSerializer.Serialize(rsaParameters.ToDictionary(), opts);

            Console.WriteLine(json);

            // Assert
            Assert.NotNull(json);
        }
Example #6
0
 private void AddConverters(ref System.Text.Json.JsonSerializerOptions settings)
 {
     if (Converters != null && Converters.Any())
     {
         foreach (var converter in Converters.Where(_ => _ != null))
         {
             var assembly = AppDomain.CurrentDomain.GetAssemblies().AsEnumerable().Where(_ => _.FullName?.Split(',')[0] == converter.Assembly).FirstOrDefault();
             if (null != assembly)
             {
                 try
                 {
                     Type converterType = System.Reflection.Assembly.LoadFrom(assembly.Location).GetType(converter.Type);
                     if (typeof(System.Text.Json.Serialization.JsonConverter).IsAssignableFrom(converterType))
                     {
                         System.Text.Json.Serialization.JsonConverter obj = null;
                         try
                         {
                             // try parms object[] parameters
                             obj = (System.Text.Json.Serialization.JsonConverter)Activator.CreateInstance(
                                 converterType,
                                 new object[] {
                                 new Microsoft.AspNetCore.Http.HttpContextAccessor()
                             });
                         }
                         catch
                         {
                             // Try parameterless ctor
                             obj = (System.Text.Json.Serialization.JsonConverter)Activator.CreateInstance(converterType);
                         }
                         if (obj != null)
                         {
                             settings.Converters.Add(obj);
                         }
                     }
                 }
                 catch { }
             }
         }
     }
 }
Example #7
0
        /// <summary>
        /// 使用指定路由和路由处理程序初始化 <see cref="AshxRouteData"/> 类的新实例。
        /// </summary>
        /// <param name="routeContext">封装与所定义路由匹配的 HTTP 请求的相关信息。</param>
        /// <param name="jsonOptions">json配置对象</param>
        public AshxRouteData(RouteContext routeContext, System.Text.Json.JsonSerializerOptions jsonOptions)
        {
            this.JsonOptions = jsonOptions;

            this.RouteContext = routeContext;
            this.GetRouteData = routeContext.RouteData;
            this.HttpContext  = routeContext.HttpContext;

            this.HttpContext.Request.RouteValues = this.GetRouteData.Values;
            //this.Service = this.HttpContext.RequestServices;
            this.IsAshx = true;
            try
            {
                this.Area       = GetRequiredString("area");
                this.Controller = GetRequiredString("controller");
                this.Action     = GetRequiredString("action");
            }
            catch (Exception)
            {
                throw HttpContext.AddHttpException(404, string.Format(System.Globalization.CultureInfo.CurrentCulture, "找不到该路由的控制器,,URL: {0}", new object[] { this.HttpContext.Request.Path }));
            }
        }
Example #8
0
        /// <summary>
        /// (Serialize)JSON 序列化
        /// </summary>
        /// <param name="implType"></param>
        /// <param name="value"></param>
        /// <param name="inputType"></param>
        /// <param name="writeIndented"></param>
        /// <param name="ignoreNullValues"></param>
        /// <returns></returns>
        public static string SJSON(JsonImplType implType, object?value, Type?inputType = null, bool writeIndented = false, bool ignoreNullValues = false)
        {
            switch (implType)
            {
            case JsonImplType.SystemTextJson:
                var options = new SJsonSerializerOptions
                {
                    Encoder          = JavaScriptEncoder.UnsafeRelaxedJsonEscaping,
                    WriteIndented    = writeIndented,
                    IgnoreNullValues = ignoreNullValues
                };
                return(SJsonSerializer.Serialize(value, inputType ?? value?.GetType() ?? typeof(object), options));

            default:
                var formatting = writeIndented ? Formatting.Indented : Formatting.None;
                var settings   = ignoreNullValues ? new JsonSerializerSettings
                {
                    NullValueHandling = NullValueHandling.Ignore
                } : null;
                return(SerializeObject(value, inputType, formatting, settings));
            }
        }
Example #9
0
        public async Task InvokeAsync(HttpContext context)
        {
            try
            {
                await _next(context);
            }
            catch (System.Exception ex)
            {
                _logger.LogError(ex, ex.Message);
                context.Response.ContentType = "application/json";
                context.Response.StatusCode  = (int)System.Net.HttpStatusCode.InternalServerError;
                var response = _env.IsDevelopment()
                ? new ApiException((int)HttpStatusCode.InternalServerError, ex.Message, ex.StackTrace.ToString())
                : new ApiException((int)HttpStatusCode.InternalServerError);

                var options = new System.Text.Json.JsonSerializerOptions {
                    PropertyNamingPolicy = System.Text.Json.JsonNamingPolicy.CamelCase
                };
                var json = System.Text.Json.JsonSerializer.Serialize(response, options);

                await context.Response.WriteAsync(json);
            }
        }
Example #10
0
        /// <summary>
        /// Deserialize the JSON stream into a .Net object.
        /// For .Net Core/.Net 5.0 uses System.Text.Json
        /// for .Net 4.5.2 uses System.Runtime.Serialization.Json
        /// </summary>
        /// <param name="type">Object type</param>
        /// <param name="stream">JSON stream</param>
        /// <returns>object of type <typeparamref name="type"/></returns>
        private static object DeserializeJson(Type type, Stream stream)
        {
#if NETCOREAPP
            var options = new System.Text.Json.JsonSerializerOptions
            {
                PropertyNameCaseInsensitive = true,
                IgnoreNullValues            = true,
            };

            options.Converters.Add(new CefSharp.Internals.Json.JsonEnumConverterFactory());

            // TODO: use synchronus Deserialize<T>(Stream) when System.Text.Json gets updated
            var memoryStream = new MemoryStream((int)stream.Length);
            stream.CopyTo(memoryStream);

            return(System.Text.Json.JsonSerializer.Deserialize(memoryStream.ToArray(), type, options));
#else
            var settings = new System.Runtime.Serialization.Json.DataContractJsonSerializerSettings();
            settings.UseSimpleDictionaryFormat = true;

            var dcs = new System.Runtime.Serialization.Json.DataContractJsonSerializer(type, settings);
            return(dcs.ReadObject(stream));
#endif
        }