首页 > 编程语言 >C# jsonconvert and binaryformater both in serialize and deserialize

C# jsonconvert and binaryformater both in serialize and deserialize

时间:2024-09-14 12:46:41浏览次数:1  
标签:both string deserialize C# items System new using public

public DelCmd ExportAllCmd { get; set; }
public DelCmd ExportAllBinaryFormatterCmd { get; set; }
public DelCmd DeserializeJsonFileCmd { get; set; }
public DelCmd DeserializeBinFileCmd { get; set; }


 private void InitCmds()
{ 
    ExportAllCmd = new DelCmd(ExportAllCmdExecuted);
    ExportAllBinaryFormatterCmd = new DelCmd(ExportAllBinaryFormatterCmdExecuted);
    DeserializeJsonFileCmd = new DelCmd(DeserializeJsonFileCmdExecuted);
    DeserializeBinFileCmd = new DelCmd(DeserializeBinFileCmdExecuted);
}


 private void DeserializeBinFileCmdExecuted(object obj)
 {
     string binFile = "BinFormatter202409141240168002_378cf4d8-63ed-451d-9a42-2d240d8f386f.bin";
     if (File.Exists(binFile))
     {
         try
         {
             StringBuilder costBuilder = new StringBuilder();
             Stopwatch watch = new Stopwatch();
             BinaryFormatter binFormatter = new BinaryFormatter();
             using (FileStream fs = new FileStream(binFile, FileMode.Open, FileAccess.Read))
             {
                 watch.Start();
                 var booksList = (List<Book>)binFormatter.Deserialize(fs);
                 if (booksList != null && booksList.Any())
                 {
                     watch.Stop();
                     costBuilder.AppendLine($"BinaryFormatter Deserialize cost:{watch.ElapsedMilliseconds},count:{booksList.Count}");
                     string costMsg = costBuilder.ToString();
                     File.AppendAllText("cost.txt", costMsg + "\n");
                     MessageBox.Show(costMsg, "Time cost", MessageBoxButton.OK);
                 }
             }
         }
         catch (Exception ex)
         {
             MessageBox.Show(ex.Message);
         }
     }
 }

 private void DeserializeJsonFileCmdExecuted(object obj)
 {
     string jsonFile = "JsonConvert202409141240130088_ae3c2d74-b0b8-405b-add4-6aafd132b2b2.json";
     
     StringBuilder costBuilder = new StringBuilder();
     
     if(File.Exists(jsonFile))
     {
         try
         {
             Stopwatch watch = new Stopwatch();
             string jsonStr = File.ReadAllText(jsonFile);
             watch.Start();
             var booksList = JsonConvert.DeserializeObject<List<Book>>(jsonStr);
             watch.Stop();
             if (booksList != null && booksList.Any())
             {
                 costBuilder.AppendLine($"JsonConvert Deserialize cost:{watch.ElapsedMilliseconds},count:{booksList.Count}");
                 string costMsg = costBuilder.ToString();
                 File.AppendAllText("cost.txt", costMsg + "\n");
                 MessageBox.Show(costMsg, "Time cost", MessageBoxButton.OK);
             }
         }
         catch (Exception ex)
         {
             MessageBox.Show(ex.Message);
         } 
     }
 }

 private void ExportAllBinaryFormatterCmdExecuted(object obj)
 {
     var dg = obj as DataGrid;
     if (dg != null)
     {
         var items = dg.ItemsSource.Cast<Book>()?.ToList();
         if (items != null && items.Any())
         {
             string allJsonFile = $"BinFormatter{DateTime.Now.ToString("yyyyMMddHHmmssffff")}_{Guid.NewGuid().ToString()}.bin";
             using (FileStream fs = new FileStream(allJsonFile, FileMode.OpenOrCreate, FileAccess.ReadWrite))
             {
                 BinaryFormatter binFormatter = new BinaryFormatter();
                 binFormatter.Serialize(fs, items);
             }
             MessageBox.Show($"Exported at:\n{allJsonFile}","BinFormatter Export successfully!", MessageBoxButton.OK);
         }
     }
 }

 private void ExportAllCmdExecuted(object obj)
 {
     var dg = obj as DataGrid;
     if (dg != null)
     {
         var items = dg.ItemsSource.Cast<Book>()?.ToList();
         if (items != null && items.Any())
         {
             string allJsonFile = $"JsonConvert{DateTime.Now.ToString("yyyyMMddHHmmssffff")}_{Guid.NewGuid().ToString()}.json";
            
             string jsonStr = JsonConvert.SerializeObject(items);
             File.AppendAllText(allJsonFile, jsonStr);
             MessageBox.Show($"Exported at:\n{allJsonFile}", "JsonConvert Export successfully!", MessageBoxButton.OK);
         }
     }
 }        

 private void ExportSelectedCmdExecuted(object obj)
 {
     var dg = obj as DataGrid;
     if (dg != null)
     {
         var items = dg.SelectedItems.Cast<Book>()?.ToList();
         if (items != null && items.Any())
         {
             string jsonStr = JsonConvert.SerializeObject(items, formatting: Formatting.Indented);
             string selectedFile = $"Selected{DateTime.Now.ToString("yyyyMMddHHmmssffff")}_{Guid.NewGuid().ToString()}.json";
             File.AppendAllText(selectedFile, jsonStr);
             MessageBox.Show($"Exported at:\n{selectedFile}", "Export successfully!", MessageBoxButton.OK);
         }
     }
 }

 

 

 

 

 

 

 

BinaryFormatter's size is smaller than jsonconvert but spend more time.

 

<Window x:Class="WpfApp365.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:WpfApp365"
        mc:Ignorable="d"
        WindowState="Maximized"
        Title="MainWindow" Height="450" Width="800">
    <Window.DataContext>
        <local:BookVM/>
    </Window.DataContext>
    <Grid>
        <DataGrid x:Name="dg"
                  ItemsSource="{Binding BooksCollection,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"
                  VirtualizingPanel.IsVirtualizing="True"
                  VirtualizingPanel.VirtualizationMode="Recycling"
                  VirtualizingPanel.IsContainerVirtualizable="True"
                  SelectionMode="Extended"
                  AutoGenerateColumns="False"
                  CanUserAddRows="False">
            <DataGrid.ContextMenu>
                <ContextMenu>
                    <MenuItem Header="Export Selected" Command="{Binding ExportSelectedCmd}"
               CommandParameter="{Binding RelativeSource={RelativeSource Mode=FindAncestor,
                        AncestorType=ContextMenu},Path=PlacementTarget}"/>
                    <MenuItem Header="Export All NewtonJson" Command="{Binding ExportAllCmd}"
               CommandParameter="{Binding RelativeSource={RelativeSource Mode=FindAncestor,
                        AncestorType=ContextMenu},Path=PlacementTarget}"/>
                    <MenuItem Header="Export All BinaryFormatter" Command="{Binding ExportAllBinaryFormatterCmd}"
               CommandParameter="{Binding RelativeSource={RelativeSource Mode=FindAncestor,
         AncestorType=ContextMenu},Path=PlacementTarget}"/>
                    <MenuItem Header="Deserialize Json File"
                              Command="{Binding DeserializeJsonFileCmd}"/>
                    <MenuItem Header="Deserialize Binary File"
           Command="{Binding DeserializeBinFileCmd}"/>
                </ContextMenu>
            </DataGrid.ContextMenu>           
            <DataGrid.Columns>
                <DataGridTextColumn Header="Id" Binding="{Binding Id}"/>
                <DataGridTextColumn Header="Name" Binding="{Binding Name}"/>
                <DataGridTextColumn Header="Title" Binding="{Binding Title}"/>
                <DataGridTextColumn Header="Topic" Binding="{Binding Topic}"/>
                <DataGridTemplateColumn Header="Image">
                    <DataGridTemplateColumn.CellTemplate>
                        <DataTemplate>
                            <local:ImageTbk ImgUrl="{Binding DataContext.PicUrl,RelativeSource={RelativeSource Mode=FindAncestor,AncestorType={x:Type DataGridRow}}}"
                                            TbkStr="{Binding DataContext.Name,RelativeSource={RelativeSource Mode=FindAncestor,AncestorType={x:Type DataGridRow}}}"/>
                        </DataTemplate>
                    </DataGridTemplateColumn.CellTemplate>
                </DataGridTemplateColumn>
            </DataGrid.Columns>
        </DataGrid>
    </Grid>
</Window>



//cs
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.IO;
using Microsoft.SqlServer.Server;
using System.Runtime.Serialization.Formatters.Binary;
using System.Diagnostics;
using System.Text.RegularExpressions;

namespace WpfApp365
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }
    }

    public class BookVM : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;
        private void OnPropertyChanged(string propertyName)
        {
            var handler = PropertyChanged;
            if(handler!=null)
            {
                handler?.Invoke(this, new PropertyChangedEventArgs(propertyName));
            }
        }

        public BookVM()
        {
            InitData();
            InitCmds();
        }

        private void InitCmds()
        {
            ExportSelectedCmd = new DelCmd(ExportSelectedCmdExecuted);
            ExportAllCmd = new DelCmd(ExportAllCmdExecuted);
            ExportAllBinaryFormatterCmd = new DelCmd(ExportAllBinaryFormatterCmdExecuted);
            DeserializeJsonFileCmd = new DelCmd(DeserializeJsonFileCmdExecuted);
            DeserializeBinFileCmd = new DelCmd(DeserializeBinFileCmdExecuted);
        }

        private void DeserializeBinFileCmdExecuted(object obj)
        {
            string binFile = "BinFormatter202409141240168002_378cf4d8-63ed-451d-9a42-2d240d8f386f.bin";
            if (File.Exists(binFile))
            {
                try
                {
                    StringBuilder costBuilder = new StringBuilder();
                    Stopwatch watch = new Stopwatch();
                    BinaryFormatter binFormatter = new BinaryFormatter();
                    using (FileStream fs = new FileStream(binFile, FileMode.Open, FileAccess.Read))
                    {
                        watch.Start();
                        var booksList = (List<Book>)binFormatter.Deserialize(fs);
                        if (booksList != null && booksList.Any())
                        {
                            watch.Stop();
                            costBuilder.AppendLine($"BinaryFormatter Deserialize cost:{watch.ElapsedMilliseconds},count:{booksList.Count}");
                            string costMsg = costBuilder.ToString();
                            File.AppendAllText("cost.txt", costMsg + "\n");
                            MessageBox.Show(costMsg, "Time cost", MessageBoxButton.OK);
                        }
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
            }
        }

        private void DeserializeJsonFileCmdExecuted(object obj)
        {
            string jsonFile = "JsonConvert202409141240130088_ae3c2d74-b0b8-405b-add4-6aafd132b2b2.json";
            
            StringBuilder costBuilder = new StringBuilder();
            
            if(File.Exists(jsonFile))
            {
                try
                {
                    Stopwatch watch = new Stopwatch();
                    string jsonStr = File.ReadAllText(jsonFile);
                    watch.Start();
                    var booksList = JsonConvert.DeserializeObject<List<Book>>(jsonStr);
                    watch.Stop();
                    if (booksList != null && booksList.Any())
                    {
                        costBuilder.AppendLine($"JsonConvert Deserialize cost:{watch.ElapsedMilliseconds},count:{booksList.Count}");
                        string costMsg = costBuilder.ToString();
                        File.AppendAllText("cost.txt", costMsg + "\n");
                        MessageBox.Show(costMsg, "Time cost", MessageBoxButton.OK);
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                } 
            }
        }

        private void ExportAllBinaryFormatterCmdExecuted(object obj)
        {
            var dg = obj as DataGrid;
            if (dg != null)
            {
                var items = dg.ItemsSource.Cast<Book>()?.ToList();
                if (items != null && items.Any())
                {
                    string allJsonFile = $"BinFormatter{DateTime.Now.ToString("yyyyMMddHHmmssffff")}_{Guid.NewGuid().ToString()}.bin";
                    using (FileStream fs = new FileStream(allJsonFile, FileMode.OpenOrCreate, FileAccess.ReadWrite))
                    {
                        BinaryFormatter binFormatter = new BinaryFormatter();
                        binFormatter.Serialize(fs, items);
                    }
                    MessageBox.Show($"Exported at:\n{allJsonFile}","BinFormatter Export successfully!", MessageBoxButton.OK);
                }
            }
        }

        private void ExportAllCmdExecuted(object obj)
        {
            var dg = obj as DataGrid;
            if (dg != null)
            {
                var items = dg.ItemsSource.Cast<Book>()?.ToList();
                if (items != null && items.Any())
                {
                    string allJsonFile = $"JsonConvert{DateTime.Now.ToString("yyyyMMddHHmmssffff")}_{Guid.NewGuid().ToString()}.json";
                   
                    string jsonStr = JsonConvert.SerializeObject(items);
                    File.AppendAllText(allJsonFile, jsonStr);
                    MessageBox.Show($"Exported at:\n{allJsonFile}", "JsonConvert Export successfully!", MessageBoxButton.OK);
                }
            }
        }        

        private void ExportSelectedCmdExecuted(object obj)
        {
            var dg = obj as DataGrid;
            if (dg != null)
            {
                var items = dg.SelectedItems.Cast<Book>()?.ToList();
                if (items != null && items.Any())
                {
                    string jsonStr = JsonConvert.SerializeObject(items, formatting: Formatting.Indented);
                    string selectedFile = $"Selected{DateTime.Now.ToString("yyyyMMddHHmmssffff")}_{Guid.NewGuid().ToString()}.json";
                    File.AppendAllText(selectedFile, jsonStr);
                    MessageBox.Show($"Exported at:\n{selectedFile}", "Export successfully!", MessageBoxButton.OK);
                }
            }
        }

        private void InitData()
        {
            var imgsList = System.IO.Directory.GetFiles(@"../../Images");
            int imgsCnt = imgsList.Count();
            BooksCollection = new ObservableCollection<Book>();

            for (int i=0;i<100000;i++)
            {
                BooksCollection.Add(new Book()
                {
                    Id = i + 1,
                    Name = $"Name_{i + 1}",
                    PicUrl = $"{imgsList[i % imgsCnt]}",
                    Title = $"Title_{i + 1}",
                    Topic=$"Topic_{Guid.NewGuid().ToString("N")}"
                });
            }
        }

        private ObservableCollection<Book> booksCollection;
        public ObservableCollection<Book> BooksCollection
        {
            get
            {
                return booksCollection;
            }
            set
            {
                if(value!=booksCollection)
                {
                    booksCollection = value;
                    OnPropertyChanged(nameof(BooksCollection));
                }
            }
        }

        public DelCmd ExportSelectedCmd { get; set; }
        public DelCmd ExportAllCmd { get; set; }
        public DelCmd ExportAllBinaryFormatterCmd { get; set; }
        public DelCmd DeserializeJsonFileCmd { get; set; }
        public DelCmd DeserializeBinFileCmd { get; set; }
    }

    [Serializable]
    public class Book
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string PicUrl { get; set; }
        public string Title { get; set; }
        public string Topic { get; set; }
    }

    public class DelCmd : ICommand
    {
        public event EventHandler CanExecuteChanged
        {
            add
            {
                CommandManager.RequerySuggested += value;
            }
            remove
            {
                CommandManager.RequerySuggested -= value;
            }
        }

        private Action<object> execute;
        private Predicate<object> canExecute;

        public DelCmd(Action<object> executeValue,Predicate<object> canExecuteValue)
        {
            execute= executeValue;
            canExecute= canExecuteValue;
        }

        public DelCmd(Action<object> executeValue):this(executeValue,null)
        {
            
        }

        public bool CanExecute(object parameter)
        {
            if(canExecute==null)
            {
                return true;
            }
            return canExecute(parameter);
        }

        public void Execute(object parameter)
        {
            execute(parameter);
        }
    }
}


//usercontrol
//xaml
<UserControl x:Class="WpfApp365.ImageTbk"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
             xmlns:local="clr-namespace:WpfApp365"
             mc:Ignorable="d" 
             d:DesignHeight="450" d:DesignWidth="800">
    <Grid>
        <Image Source="{Binding ImgUrl,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"
               Width="100" Height="250"/>
        <TextBlock Text="{Binding TkbStr,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"/>
    </Grid>
</UserControl>


//cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace WpfApp365
{
    /// <summary>
    /// Interaction logic for ImageTbk.xaml
    /// </summary>
    public partial class ImageTbk : UserControl
    {
        public ImageTbk()
        {
            InitializeComponent();
            this.DataContext = this;
        }



        public string ImgUrl
        {
            get { return (string)GetValue(ImgUrlProperty); }
            set { SetValue(ImgUrlProperty, value); }
        }

        // Using a DependencyProperty as the backing store for ImgUrl.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty ImgUrlProperty =
            DependencyProperty.Register("ImgUrl", typeof(string), 
                typeof(ImageTbk), new PropertyMetadata(""));




        public string TbkStr
        {
            get { return (string)GetValue(TbkStrProperty); }
            set { SetValue(TbkStrProperty, value); }
        }

        // Using a DependencyProperty as the backing store for TbkStr.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty TbkStrProperty =
            DependencyProperty.Register("TbkStr", typeof(string), 
                typeof(ImageTbk), new PropertyMetadata(""));


    }
}

 

标签:both,string,deserialize,C#,items,System,new,using,public
From: https://www.cnblogs.com/Fred1987/p/18413753

相关文章

  • PbootCMS模板中那些url怎么调用
    在PBootCMS中,httpurl、pageurl 和 sitedomain 标签用于获取当前站点的相关网址信息。以下是详细的使用说明和示例代码。1.当前站点网址标签说明{pboot:httpurl}:自适应获取当前访问网址,主要用于需要使用网站路径前缀的情况。示例输出plaintext https://www.xxx.......
  • PbootCMS怎么调用网站的留言数和文章总数
    在PBootCMS中,可以使用 pboot:sql 标签来自定义任意查询语句并循环输出。下面详细介绍如何使用此标签来调用网站的留言数和文章总数。1.调用网站的留言数示例代码html {pboot:sqlsql="selectcount(id)astotalfromay_message"}留言合计:[sql:total]条{/pbo......
  • c++代理类
    c++中代理类的学习https://blog.csdn.net/lcg910978041/article/details/51468680C++代理类是为了解决这样的问题: 容器通常只能包含一种类型的对象,所以很难在容器中存储对象本身。怎样设计一个c++容器,使它有能力包含类型不同而彼此相关的对象? 代理运行起来和他所代表的......
  • 开源模型应用落地-qwen2-7b-instruct-LoRA微调-unsloth(让微调起飞)-单机单卡-V100(十七)
    一、前言  本篇文章将在v100单卡服务器上,使用unsloth去高效微调QWen2系列模型,通过阅读本文,您将能够更好地掌握这些关键技术,理解其中的关键技术要点,并应用于自己的项目中。  使用unsloth能够使模型的微调速度提高2-5倍。在处理大规模数据或对时间要求较高的场景下......
  • PbootCMS会员相关标签调用
    在PBootCMS中,你可以通过一系列会员相关的标签来实现会员管理功能。以下是对这些标签的具体说明和使用方法:1.基本标签标签说明{pboot:ucenter}:个人中心地址{pboot:login}:登录地址{pboot:register}:注册地址{pboot:umodify}:资料修改地址{pboot:logout}:退出登录地址{pboot......
  • 没想到一个 HTTP Client 居然考虑这么多场景...
    在项目开发过程中,HTTP请求可以说是非常常见的需求,无论是与外部API交互,还是实现微服务间的通信。这篇文章以Go语言为背景,探讨HTTP客户端的构建。Go的标准库net/http虽然功能强大,但在进行复杂的HTTP请求时,往往需要开发者写很多重复代码。在这种情况下,开发者就需要一个既......
  • ml语法转C语法,转译器成品
    ml编译器成品Project12024-seealsoprojectclarifications(updated5pm28thAug)andmarkingrubric成品(Price500)w,e,c,h,a,t:help-assignmentThegoalofthisprojectistoimplementaC11programtotranslateprogramswritteninasmallmi......
  • PbootCMS首页调用公司简介等频道内容
    在PBootCMS中,调用专题频道内容(如公司简介、联系我们等)可以通过 content 标签来实现。以下是具体的使用方法和示例代码:1. content 标签的基本用法参数说明id:文章内容或专题内容对应的ID。scode:栏目管理中该栏目的ID。示例代码html {pboot:contentid=1}......
  • PbootCMS模板自动生成当前页面二维码
    在PBootCMS中,qrcode 标签用于生成对应文本的二维码图片。这对于产品列表页或详情页为每个产品生成二维码非常有用。以下是详细的使用说明和示例代码。1. qrcode 标签的基本用法参数说明string=*:指定生成二维码的文本内容。2.示例代码生成产品详情页的二维码假设你需......
  • 一个小技巧,巧妙的使用 sync.Pool 减少 GC 压力,提升性能!
    Go语言的sync.Pool本质是用来保存和复用临时对象,以减少内存分配,降低GC压力,比如需要使用一个对象,就去Pool里面拿,如果拿不到就分配一份,这比起不停生成新的对象,用完了再等待GC回收要高效的多。sync.Pool是临时对象池,存储的是临时对象,不可以用它来存储socket长连接和数据库......