Created
April 10, 2017 05:21
-
-
Save tetya/36ca289fe88ff83830e06ee7e9ce3e51 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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