对字典不熟,序列化一个文件,读取反序列化,这样子应该可以了吧
引用里面添加 System.Runtime.Serialization
程序代码:
using System;
using System.Collections.Generic;
using using System.Data;
using System.Drawing;
using using System.Linq;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Direct
{
public partial class Form1 : Form
{
[DataContract]
public class MyClass
{
[DataMember]
public Dictionary<int, string> myDictionary = new Dictionary<int, string>();
}
MyClass myClass = new MyClass();
public Form1()
{
InitializeComponent();
myClass.myDictionary.Add(1, "C#");
myClass.myDictionary.Add(2, "C++");
myClass.myDictionary.Add(3, "");
myClass.myDictionary.Add(4, "MVC");
}
private void button1_Click(object sender, EventArgs e)
{
ObjectToJson(myClass, "123.json");
}
private void button2_Click(object sender, EventArgs e)
{
myClass.myDictionary.Clear();
myClass =JsonFileToObject<MyClass>("123.json");
}
/// 将对象序列化为json文件
public static void ObjectToJson<T>(T t, string path) where T : class
{
DataContractJsonSerializer formatter = new DataContractJsonSerializer(typeof(T));
using (FileStream stream = new FileStream(path, FileMode.Create))
{
formatter.WriteObject(stream, t);
}
}
/// json字符串转成对象
public static T JsonToObject<T>(string json) where T : class
{
DataContractJsonSerializer formatter = new DataContractJsonSerializer(typeof(T));
using (MemoryStream stream = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(json)))
{
T result = formatter.ReadObject(stream) as T;
return result;
}
}
/// json文件转成对象
public static T JsonFileToObject<T>(string path) where T : class
{
string str = File.ReadAllText(path, Encoding.UTF8);
return JsonToObject<T>(str);
}
}
}
[此贴子已经被作者于2022-8-15 20:13编辑过]