Skip to content

Instantly share code, notes, and snippets.

@tetya
Created April 10, 2017 05:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tetya/36ca289fe88ff83830e06ee7e9ce3e51 to your computer and use it in GitHub Desktop.
Save tetya/36ca289fe88ff83830e06ee7e9ce3e51 to your computer and use it in GitHub Desktop.
using UnityEngine;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;
public class JsonTest : MonoBehaviour
{
//---
[System.Serializable]
public class Item
{
public int id;
public string name;
public string description;
}
//---
string savePath = "Assets/Test/JsonTest/saveData.json";
// Use this for initialization
void Start ()
{
string itemJson = "{ \"id\": 100, \"name\": \"テストアイテム\", \"description\": \"説明だよ\" }";
Item item = JsonUtility.FromJson<Item>(itemJson);
save(item);
TestLog(item);
Debug.Log("---");
item = load();
TestLog(item);
}
//セーブ
private void save(Item item)
{
string json = JsonUtility.ToJson(item);
BinaryFormatter bf = new BinaryFormatter();
FileStream file = File.Create(savePath);
bf.Serialize(file, json);
file.Close();
}
//ロード
private Item load()
{
BinaryFormatter bf = new BinaryFormatter();
FileStream file = File.Open(savePath, FileMode.Open);
string json = (string)bf.Deserialize(file);
file.Close();
return JsonUtility.FromJson<Item>(json);
}
//確認用のログを表示
private void TestLog(Item item)
{
Debug.Log("item id " + item.id);
Debug.Log("item name " + item.name);
Debug.Log("item description " + item.description);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment