LoginSignup
9
5

More than 3 years have passed since last update.

Unity/IL2CPPでJSONを使う

Last updated at Posted at 2020-03-20

UnityのIL2CPPで、普通にJSONライブラリを使おうとするとReflection関係でエラーが発生して使えないため、IL2CPPでも使えるライブラリとその使い方を書いておきます。

使ったバージョンは、 Unity 2019.3 です。

1. JsonUtility

Unity標準のJSONライブラリです。Dictionaryなど一部の型には対応していませんが、IL2CPP下でも使えます。

using System;
using UnityEngine;

[Serializable]
public class Item {
    public string Name;
    public int Value;
}

string json = JsonUtility.ToJson(item);
Item item = JsonUtility.FromJson<Item>(json);

2. Newtonsoft.Json

普通に使おうとすると他のライブラリ同様、エラーになりますが、以下の手順で動作させることができました。

  1. Newtonsoft.Json の Nuget Package をダウンロード
  2. 拡張子の .nupkg.zip に変えて解凍
  3. lib\netstandard2.0 以下にある dll ファイルを Unity のプロジェクトに追加 (lib\net45 ではない)
  4. 加えて以下の link.xml もプロジェクトに追加
<linker>
<assembly fullname="System.Core">
<type fullname="System.Linq.Expressions.Interpreter.LightLambda" preserve="all" />
</assembly>
</linker>

あとは通常通り使えるはずです。

using Newtonsoft.Json;

string json = JsonConvert.SerializeObject(item);
Item item = JsonConvert.DeserializeObject<Item>(json);

ちなみに Newtonsoft.Json for Unity が使えるとの情報もありましたが、手元ではエラーで動きませんでした...

参考リンク

https://stackoverflow.com/a/59486989/8320511
https://issuetracker.unity3d.com/issues/il2cpp-notsupportedexceptions-exception-is-thrown-in-build-with-newtonsoft-dot-json-plugin

その他

Utf8Json には、 IL2CPP 用に事前コード生成の機能があるのですが、シリアライズするクラスにジェネリクスを使っていたせいか、これも手元ではエラーで動かすことができませんでした...

こちらで動かなかったライブラリも、バージョンや環境によってはうまくいくこともあると思いますので、いろいろ試してみてください。

9
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
9
5