UnityでJSONの読み書き(Utilsクラスつき)

 一応、Unity標準にJsonUtilityというものはあるんですが、

ため、使用を断念。速度は速いそうですが・・・



他に使えるライブラリがないか探した結果、NewtonsoftのJson.NETを発見。
(もっと良いものをご存じの方がいたら教えていただけると幸いです)

どうやらUnity側がパッケージを提供してくれているようなので、
インストールも簡単に行えるようです。
公式のインストール方法はこちらですが、
ややわかりづらいと思いますので以下にまとめました。
  1. Unityの「Window」→「Package Manager」


  2. 「+」→「Add package by name...」


  3.  「com.unity.nuget.newtonsoft-json」と入力、「Add」
    (バージョンは空欄のままにしておけば最新バージョンが取得される)


  4. Newtonsoft Jsonの最新版がインストールされたのを確認できます。
    (2023/10/14時点の最新は3.2.1)


後は公式の情報を頼りにプログラムを書けばいいのですが、おススメの設定があるらしく、
ついでにUtilsクラス化したのが以下です。
※2023/11/22 SaveJsonの引数の順番を変更
Copy
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.IO;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
public static class NewtonsoftJsonUtils
{
// JSON化の設定
// 参考 https://qiita.com/matchyy/items/b1cd6f3a2a93749774da#tldr
public static readonly JsonSerializerSettings JSON_SETTINGS = new JsonSerializerSettings
{
ReferenceLoopHandling = ReferenceLoopHandling.Ignore,
ContractResolver = new CamelCasePropertyNamesContractResolver()
};
public static readonly JsonSerializer SERIALIZER = JsonSerializer.CreateDefault(JSON_SETTINGS);
public static string GetCurrentDirectory()
{
// 開発中は C:/Users/%USERNAME%/AppData/LocalLow/DefaultCompany/プロジェクト名
return Application.persistentDataPath;
}
/// <summary>
/// Jsonファイルを保存
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="filename">ファイル名</param>
/// <param name="json"></param>
/// /// <param name="directory">ディレクトリ(空の場合はApplication.persistentDataPathになる)</param>
public static void SaveJson<T>(T json, string filename, string directory = "")
{
// ディレクトリの指定がない場合はカレント
if (string.IsNullOrEmpty(directory)) {
directory = GetCurrentDirectory();
}
// 参考
// https://www.newtonsoft.com/json/help/html/SerializeWithJsonSerializerToFile.htm
using (StreamWriter file = File.CreateText(Path.Combine(directory, filename)))
{
SERIALIZER.Serialize(file, json);
}
}
/// <summary>
/// Jsonファイルを読み込み
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="filename"></param>
/// <param name="directory">ディレクトリ(空の場合はApplication.persistentDataPathになる)</param>
/// <returns></returns>
public static T LoadJson<T>(string filename, string directory = "")
{
// ディレクトリの指定がない場合はカレント
if (string.IsNullOrEmpty(directory)) {
directory = GetCurrentDirectory();
}
using (StreamReader file = File.OpenText(Path.Combine(directory, filename)))
{
// なぜかジェネリックのメソッドが用意されてない
return (T)SERIALIZER.Deserialize(file, typeof(T));
}
}
}

うっかりstringを経由して無駄な時間を使わず、直接ファイル変換するのがポイント。




デフォルトディレクトリは調べた限り
Application.persistentDataPathを使うのが良さそうですが、
Unity素人なので正直自信がありません。

なんかもっと良い方法があれば教えていただけると幸いです。

コメント