LoginSignup
0
1

More than 5 years have passed since last update.

[C#][Visual Studio] T4テキストテンプレート 内でJSON.NET(3rd Party製ライブラリ)を利用する

Posted at

T4テキストテンプレート 内でJSON.NET(3rd Party製ライブラリ)を利用する

T4 Template 内で外部ファイルを読み込みたい場合、System.Xml でもいいですが、Jsonを利用したい場合があると思います。
その場合、JSON.NETのようにNugetで取得したライブラリを使用したい場合は以下のようにすればよかったです。
(プロジェクト名がベタ打ちのため、あんまりきれいなやり方じゃないですけども・・・)

<#@ assembly name="$(SolutionDir)\MyProject\bin\Debug\Newtonsoft.Json.dll" #>
<#@ import namespace="Newtonsoft.Json" #>

テンプレート内で $(SolutionDir) という、ソリューションの絶対パスを取得できる変数を利用しています。

使用例

sample.tt
<#@ template debug="false" hostspecific="true" language="C#" #>
<#@ assembly name="System.Core" #>
<#@ assembly name="$(SolutionDir)\MyProject\bin\Debug\Newtonsoft.Json.dll" #>
<#@ import namespace="System.Linq" #>
<#@ import namespace="System.Text" #>
<#@ import namespace="System.IO" #>
<#@ import namespace="System.Collections.Generic" #>
<#@ import namespace="Newtonsoft.Json" #>
<#@ output extension=".cs" #>
<#
    var jsonFilePath = this.Host.ResolvePath("Config.json");
    var desirialized = JsonConvert.DeserializeObject(File.ReadAllText(jsonFilePath));
    WriteLine(desirialized.ToString());
#

この使用例ではテンプレートファイルからの相対パスを取得するために、Host.ResolvePath を使用しています。
これを利用するためには、1行目の hostspecific="true" の設定を有効にする必要があるので注意してください。

上記例で使用している Config.jsonsample.tt と同じディレクトリに配置されていることを想定しています。

参考

T4 テキスト テンプレートを使用したデザイン時コード生成
Visual Studio搭載のT4テンプレートエンジンの3通りの活用方法 - seraphyの日記
複数の入力ファイルをT4テンプレートに適用して複数のファイルを生成する - Qiita

0
1
1

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
0
1