C# c++ Json序列化与反序列

using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Runtime.Serialization.Json;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace LineControlSln.ConfigManager.DigitalConfig
{

    public partial class DigitalConfigView : UserControl
    {
        
        private DigitalParam _digitalParam;

        public DigitalConfigView()
        {
            InitializeComponent();
            LoadDigialConfig();
        }

        #region singlon
        public static DigitalConfigView CreateSingle()
        {
            if (_DigitalConfigView == null || _DigitalConfigView.IsDisposed)
            {
                _DigitalConfigView = new DigitalConfigView();
            }
            return _DigitalConfigView;
        }
        #endregion
        
        // 序列化,  把对象转成json字符串,存到文件
        private bool SaveDigialConfig()
        {
            try
            {
                string FilePath = @"DigitalConfig.xml";

                //将对象转化成Json字符串
                DataContractJsonSerializer ds = new DataContractJsonSerializer(typeof(DigitalParam));
                using (MemoryStream ms = new MemoryStream())
                {
                    ds.WriteObject(ms, _digitalParam);
                    string output = Encoding.UTF8.GetString(ms.ToArray());
                    File.WriteAllText(FilePath, output, Encoding.UTF8);
                }
            }
            catch (Exception ex)
            {
                throw;
            }
            return true;
        }
        // 反序列化,把文件string读到对象
        public void LoadDigialConfig()
        {

            try
            {
                string FilePath = @"DigitalConfig.xml";
                if (File.Exists(FilePath))
                {
                    data = JsonConvert.DeserializeObject(File.ReadAllText(FilePath));

                }
            }
            catch (Exception ex)
            {
                throw;
            }

        }
    }
}

你可能感兴趣的:(C#,c#,json,开发语言)