1. 程式人生 > >基於Unity3D的JSON檔案的儲存的實現

基於Unity3D的JSON檔案的儲存的實現

在unity的開發中,經常會用到Json來儲存資料檔案。如下我將帶領大家來實現一套json檔案的儲存系統。功能如下:

1.若沒有json檔案,將建立一個json檔案,並賦值為資料類StudentData中的資料;

2.若存在json檔案,將讀取json檔案中的資料,並賦值給資料類StudentData;

3.實現對json檔案的增,刪,改,查。

(注意:本程式碼使用LitJson.dll進行解析,需把LitJson.dll放入到Unity的Assets中的任意資料夾中 Json官網:http://www.json.org

程式碼如下:

學生資料類StudentData

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

//性別列舉
public enum SexType{
	None,Female,Male
}
[System.Serializable]
//課程分數
public class Grade{
	public float math;
	public float physics;
	public float english;
}
[System.Serializable]
//學生類
public class StudentData {
	//學號
	public float id;
	//學號
	public string name;
	//性別
	public SexType sexType=SexType.None;
	//年齡
	public int age; 
	//是否統考
	public bool bCylet;
	//成績
	public Grade grade;
	//儲存的檔名
	public const string FILENAME="StudentData";

	public StudentData(float id,string name,SexType sexType,int age,bool bCylet,Grade grade){
		this.id = id;
		this.name = name;
		this.sexType = sexType;
		this.age = age;
		this.bCylet = bCylet;
		this.grade = grade;
	}
}
Json檔案管理
using UnityEngine;
using System.Collections;
using System.IO;
using System.Text;
using System;
using LitJson;

public class JsonMgr : MonoBehaviour {
    public static JsonMgr _instance;

    //學生資料類
    public StudentData studentData;

    void Awke()
    {
        _instance = this;
    }
    void Start()
    {
		if (File.Exists(Application.dataPath + "//" + StudentData.FILENAME)) {
			studentData = ParseFile (Application.dataPath, StudentData.FILENAME);
        }
        else
        {
			CreateFile(Application.dataPath, StudentData.FILENAME, studentData);
        }
    }
    //建立json檔案
	void CreateFile(string filePath,string fileName,StudentData studentData)
    {
        StringBuilder stringBuilder = new StringBuilder();
        JsonWriter jsonWriter = new JsonWriter(stringBuilder);
        jsonWriter.WriteObjectStart();

        jsonWriter.WritePropertyName("id");
		jsonWriter.Write(studentData.id);
        jsonWriter.WritePropertyName("name");
		jsonWriter.Write(studentData.name);
		jsonWriter.WritePropertyName("sexType");
		jsonWriter.Write(studentData.sexType.ToString());
		jsonWriter.WritePropertyName("age");
		jsonWriter.Write(studentData.age);
		jsonWriter.WritePropertyName("bCylet");
		jsonWriter.Write(studentData.bCylet);

		jsonWriter.WritePropertyName ("grade");
		jsonWriter.WriteArrayStart ();

		jsonWriter.WriteObjectStart ();
		jsonWriter.WritePropertyName ("math");
		jsonWriter.Write (studentData.grade.math);
		jsonWriter.WriteObjectEnd ();
		jsonWriter.WriteObjectStart ();
		jsonWriter.WritePropertyName ("physics");
		jsonWriter.Write (studentData.grade.physics);
		jsonWriter.WriteObjectEnd ();
		jsonWriter.WriteObjectStart ();
		jsonWriter.WritePropertyName ("english");
		jsonWriter.Write (studentData.grade.english);
		jsonWriter.WriteObjectEnd ();
       
        jsonWriter.WriteArrayEnd();

        jsonWriter.WriteObjectEnd();

		FileStream fileStream = new FileStream(filePath + "//" + fileName, FileMode.OpenOrCreate, FileAccess.Write, FileShare.ReadWrite);
        StreamWriter streamWriter = new StreamWriter(fileStream);
        streamWriter.WriteLine(stringBuilder.ToString());
        streamWriter.Close();
        fileStream.Close();
        fileStream.Dispose();
    }
    //解析json檔案
	private StudentData ParseFile(string filePath, string fileName)
    {
		StudentData studentData = null;
		if (File.Exists(filePath + "//" + fileName))
        {
			float id;
			string name;
			SexType sexType=SexType.None;
			int age;
			bool bCylet;
			Grade grade=new Grade();

            FileStream fileStream = new FileStream(filePath + "//" + fileName, FileMode.Open, FileAccess.Read, FileShare.Read);
            StreamReader streamReader = new StreamReader(fileStream);
			string strData = streamReader.ReadToEnd ();
            JsonData jsonData = JsonMapper.ToObject(strData);

			id = float.Parse (jsonData ["id"].ToString ());
			name = jsonData["name"].ToString();
			sexType = (SexType)Enum.Parse (typeof(SexType), jsonData ["sexType"].ToString ());
			age = int.Parse (jsonData ["age"].ToString());
			bCylet = bool.Parse (jsonData ["bCylet"].ToString());
			grade.math = float.Parse(jsonData ["grade"] [0] ["math"].ToString ());
			grade.physics= float.Parse(jsonData ["grade"] [1] ["physics"].ToString ());
			grade.english= float.Parse(jsonData ["grade"] [2] ["english"].ToString ());

			studentData =new StudentData(id,name,sexType,age,bCylet,grade);
		}
		return studentData;
    }
    void OnApplicationQuit()
    {
		CreateFile(Application.dataPath, StudentData.FILENAME,studentData);
    }
}
生成的Json檔案
{
    "id": 1303070223,
    "name": "zhangsan",
    "sexType": "Male",
    "age": 23,
    "bCylet": true,
    "grade": [
        {
            "math": 96
        },
        {
            "physics": 99
        },
        {
            "english": null
        }
    ]
}