序列化与反序列化,JSON数据的写入和读取

本文介绍了在Unity3D中如何使用BinaryFormatter进行对象的序列化和反序列化,用于保存和恢复对象状态。同时,也展示了JSON作为轻量级数据交换格式的应用,包括如何创建可序列化的Users类,以及写入和读取JSON文件的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

         序列化是将一个对象转换成字节流以达到将其长期保存在内存、数据库或文件中的处理过程。它的主要目的是保存对象的状态以便以后需要的时候使用。与其相反的过程叫做反序列化。

         为了使用序列化,我们需要引入System.Runtime.Serialization.Formatters.Binary名字空间. 

void Start () {
		Write();
		Read();
    }
	
	void Write () {
		Persons p = new Persons(1001, "海涛");//将这个值传到下面的文件中
		string path = Application.dataPath + "/flie/haitao.txt";
		using (FileStream fs = new FileStream(path, FileMode.Create, FileAccess.Write))
		{
			try
			{
				BinaryFormatter bf=new BinaryFormatter();//格式化器
				bf.Serialize(fs, p);//序列化
			}
			catch(Exception e)
			{
				print(e.Message);
			}
			finally
			{
				fs.Close();
			}
		}
		
	}
	void Read()
	{
        string path = Application.dataPath + "/flie/haitao.txt";
		using (FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read))
		{
			try
			{
				BinaryFormatter bf = new BinaryFormatter();//格式化器
				Persons p = (Persons)bf.Deserialize(fs);//反序列话
				print(p.Id + "\t" + p.Name);
			}
			catch (Exception e)
			{
				print(e.Message);//打赢错误信息
			}
			finally
			{
				fs.Close();
			}
		}
	}

         JSON(JavaScript 对象简谱:JavaScript Object Notation) 是一种轻量级的数据交换格式, 易于人阅读和编写。同时也易于机器解析和生成。

         写入JOSN文件时,你需要写一个类,并且属性不封装

         我这里用一个登入注册来举例

      这是一个属性类  

using System;
//序列化类
[Serializable]
public class Users
{
    public string Id;
    public string Password;
    public Users()
    {

    }
    public Users(string id, string password)
    {
        Id = id;
        Password = password;
    }
}

写入操作

 public void Write()
    {
        string path = Application.dataPath + "/File/Users.txt";   
        Users u = new Users();
        u.Id = zhtext.text;
        u.Password = mmtext.text;
        string s = JsonUtility.ToJson(u) + "\n";//转换格式
        File.AppendAllText(path, s);
        print(s);      
    }

读取操作

    public void Rread()
    {
        string path=Application.dataPath + "/File/Users.txt";
        string[] s=File.ReadAllLines(path);
        for(int i=0;i<s.Length;i++)
        {
            Users u= JsonUtility.FromJson<Users>(s[i]);
            if(u.Id== zhtext.text&&u.Password== mmtext.text)
            {
                print("登入成功");
            }
            if(i==s.Length)
            {
                print("账号或者密码错误");
            }
        }
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值