1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Newtonsoft の Json.NET を Unity で使うときに便利な設定

Posted at

NewtonSoft の Json.NET 使っていますか?Unity 標準の JSON Utility と比較して汎用性が高く、ちょっとしたことをよしなに取り込んでくれることが多いのでよく使っています。おまけに書いた問題もありますが、それはまた別記事で。

TL;DR

以下設定しておけば、JsonSerializationException が出ることもなく、LowerCamelCase にも対応できます。

サンプルコード

        var settings = new JsonSerializerSettings
        {
            ReferenceLoopHandling = ReferenceLoopHandling.Ignore,
            ContractResolver = new CamelCasePropertyNamesContractResolver()
        };
        var json = JsonConvert.SerializeObject(target, settings);

JsonSerializationException が出てしまう

エラーサンプル

JsonSerializationException: Self referencing loop detected for property 'normalized' with type 'UnityEngine.Vector3'. Path 'normalized.normalized'.

原因

Unity の normalized のプロパティは、自身のプロパティに normalized を持っているので、このプロパティを無限に参照できることに起因しています。

解決方法

シリアライズするときにオプションを設定することで無視することができます。これだけでエラーは回避できます。

var settings = new JsonSerializerSettings {ReferenceLoopHandling = ReferenceLoopHandling.Ignore};

key は小文字だが、プロパティは大文字始まりにしたい

サーバサイドとやりとりするときに、相手方が LowerCamel を想定している場合があります。
ただフィールドやプロパティを UpperCamel にしたい場合に差異がでてしまうので、そこをうまくやる設定項目です。

解決方法

シリアライズするときにオプションを設定することで、よしなにうまくやってくれます。

var settings = new JsonSerializerSettings {ContractResolver = new CamelCasePropertyNamesContractResolver()};

参考

相手方が LowerCamel だったとしても、デシリアライズは設定なしでも Json.NET がよしなにやってくれます。

おまけ

問題だと思っていること。

  • dll で取り込んでいると、WPFビルドやiOSビルドで死ぬときがある。
    • WPFビルドの場合は、Unity からソリューションを出したタイミングで、dll を追加してあげればエラーにならないようにする方法があります。また別記事で書きます。
    • iOSビルドの場合は、dll では無理なので、PackageManager で本家 folk されたプログラムを取り込む方法があります。また別記事で書きます。
  • パフォーマンスが良くない。こちらの記事が参考になるかと。
1
2
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
1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?