当前位置: 代码迷 >> 综合 >> C# Jason 序列化到文件 和从文件反序列化到对象
  详细解决方案

C# Jason 序列化到文件 和从文件反序列化到对象

热度:95   发布时间:2024-02-27 00:23:27.0

应用:https://www.cnblogs.com/caofangsheng/p/5687994.html

以下是全部代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using Newtonsoft.Json;
using System.IO;

namespace JasonTest
{
public class Student
{
public int ID { get; set; }

    public string Name { get; set; }public int Age { get; set; }public string Sex { get; set; }}class Program{static void Serial(){//序列化对象Student one = new Student(){ ID = 1, Name = "武松", Age = 250, Sex = "男" };//序列化string jsonData = JsonConvert.SerializeObject(one);      FileStream nFile = new FileStream("jsonTest.txt", FileMode.CreateNew);StreamWriter writer = new StreamWriter(nFile);writer.Write(jsonData);writer.Close();    //写到文件Console.WriteLine(jsonData);  //显示结果Console.ReadLine();}static void DiserialData(){FileStream file = new FileStream("jsonTest.txt", FileMode.Open);StreamReader sr = new StreamReader(file);string readJson = sr.ReadToEnd();   //从文件读出来Student descJsonStu = JsonConvert.DeserializeObject<Student>(readJson);//反序列化Console.WriteLine(descJsonStu.ID);Console.WriteLine(descJsonStu.Name);Console.WriteLine(descJsonStu.Age);Console.WriteLine(descJsonStu.Sex);Console.ReadLine();}static void Main(string[] args){// Serial();   //序列化到文件DiserialData();//从文件 反序列化到对象}}}

运行结果: