Skip to content

Instantly share code, notes, and snippets.

@WestHillApps
Last active May 23, 2023 09:30
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save WestHillApps/492734060599fc8b7428 to your computer and use it in GitHub Desktop.
Save WestHillApps/492734060599fc8b7428 to your computer and use it in GitHub Desktop.
JsonUtility Test
using System;
using System.Collections.Generic;
using UnityEngine;
public class JsonUtilityTest : MonoBehaviour
{
private void Start ()
{
var orgTest = new TestClass();
orgTest.Log();
// Json化
string jsonStr = JsonUtility.ToJson(orgTest);
Debug.Log("jsonStr:" + jsonStr);
// Jsonから復元
var newTest = JsonUtility.FromJson<TestClass>(jsonStr);
newTest.Log();
}
/// <summary>
/// Json化したいクラス
/// </summary>
public class TestClass : ISerializationCallbackReceiver
{
public string str;
public int num;
public List<string> strList;
public TestClass2 test2;
public Dictionary<int, string> dic;
// Dictionaryシリアライズ化用List
public List<int> dicKeys;
public List<string> dicVals;
public TestClass ()
{
str = "テスト";
num = 10;
strList = new List<string> { "陸", "海", "空" };
test2 = new TestClass2();
dic = new Dictionary<int, string>();
dic.Add(1, "dic1");
dic.Add(2, "dic2");
dic.Add(3, "dic3");
dicKeys = new List<int>();
dicVals = new List<string>();
}
public void Log ()
{
string logStr = "str:" + str + " num:" + num;
for (int i = 0; i < strList.Count; i++) {
logStr += " list" + i + ":" + strList[i];
}
logStr += " test2.str2:" + test2.str2 + " test2.num2" + test2.num2;
foreach (var kvp in dic) {
logStr += " " + kvp.Key + ":" + kvp.Value;
}
Debug.Log(logStr);
}
/// <summary>
/// シリアライズ前イベント
/// </summary>
public void OnBeforeSerialize ()
{
// DictionaryをListとして保存
dicKeys.Clear();
dicVals.Clear();
foreach (var kvp in dic) {
dicKeys.Add(kvp.Key);
dicVals.Add(kvp.Value);
}
}
/// <summary>
/// デシリアライズ後イベント
/// </summary>
public void OnAfterDeserialize ()
{
// ListからDictionaryへ復元
dic = new Dictionary<int, string>();
for (int i = 0; i < Math.Min(dicKeys.Count, dicVals.Count); i++) {
dic.Add(dicKeys[i], dicVals[i]);
}
}
}
/// <summary>
/// Json化したいクラスに含まれるクラス
/// </summary>
[Serializable]
public class TestClass2
{
public string str2;
public int num2;
public TestClass2 ()
{
str2 = "テスト2";
num2 = 20;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment