JSON → C# クラス変換ツール
JSONから、プロパティとJsonProperty属性を備えたC#クラスを生成します。Newtonsoft.Jsonですぐに使えます。
JSONからC#クラスを生成
.NETでJSONをデシリアライズするには、まずペイロードに対応するプロパティを持つモデルクラスが必要です。このツールはそのクラスを自動で書き出します。camelCaseのキーは元のキー名を保持する[JsonProperty]属性付きのPascalCaseプロパティになり、ネストしたオブジェクトはそれぞれ独立したpartialクラスに、配列は型付き配列に、整数はlong、小数はdoubleになります。さらに、Newtonsoft.Json(Json.NET)用のコンバーター設定を含む静的なFromJsonメソッドとToJson拡張メソッドも追加されます。
使い方
- サービスが呼び出すAPIのレスポンスなど、JSONサンプルを貼り付けます。
- ルートクラスの名前を入力します(例: Product)。
- NuGetでNewtonsoft.Jsonパッケージをインストールし、ファイルをプロジェクトに追加して、QuickType名前空間を自分のものに変更したうえでProduct.FromJson(json)を呼び出します。
よくある質問
- System.Text.Jsonでも使えますか?
- 属性とヘルパーはNewtonsoft.Jsonを対象としています。System.Text.Jsonで使う場合は、プロパティはそのままにして、[JsonProperty]をSystem.Text.Json.Serializationの[JsonPropertyName]に置き換え、JsonSerializer.Deserialize<Product>(json)でデシリアライズしてください。
- 数値がlongとdoubleで生成されるのはなぜですか?
- JSONの数値には固定のサイズがないため、オーバーフローを避けられるlongとdoubleを使っています。金額にはdecimalを使うなど、ドメインに合わせてコピー後にintやdecimalへ変更してください。
- クラスがpartialで宣言されているのはなぜですか?
- partialクラスにすることで、生成されたプロパティとFromJsonヘルパーを別々の宣言に分けられます。また、生成されたファイルを編集せずに、別ファイルに独自のメンバーを追加できます。
例: JSONからC#への変換
入力JSON
{
"productId": 7,
"title": "Mechanical Keyboard",
"price": 129.99,
"inStock": true,
"tags": ["hardware", "usb-c"]
}生成されたC#(Product)
// <auto-generated />
//
// To parse this JSON data, add NuGet 'Newtonsoft.Json' then do:
//
// using QuickType;
//
// var product = Product.FromJson(jsonString);
namespace QuickType
{
using System;
using System.Collections.Generic;
using System.Globalization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
public partial class Product
{
[JsonProperty("productId")]
public long ProductId { get; set; }
[JsonProperty("title")]
public string Title { get; set; }
[JsonProperty("price")]
public double Price { get; set; }
[JsonProperty("inStock")]
public bool InStock { get; set; }
[JsonProperty("tags")]
public string[] Tags { get; set; }
}
public partial class Product
{
public static Product FromJson(string json) => JsonConvert.DeserializeObject<Product>(json, QuickType.Converter.Settings);
}
public static class Serialize
{
public static string ToJson(this Product self) => JsonConvert.SerializeObject(self, QuickType.Converter.Settings);
}
internal static class Converter
{
public static readonly JsonSerializerSettings Settings = new JsonSerializerSettings
{
MetadataPropertyHandling = MetadataPropertyHandling.Ignore,
DateParseHandling = DateParseHandling.None,
Converters =
{
new IsoDateTimeConverter { DateTimeStyles = DateTimeStyles.AssumeUniversal }
},
};
}
}