概要
.NET Core でオブジェクト (POCO) を JSON に変換する方法です。
環境
- Windows10
- Visual Studio 2019
- .NET Core 2.2
コードサンプル
サンプルコードを Github にアップしています。
https://github.com/tYoshiyuki/dotnet-core-convert-json
解説
変換対象のクラスを準備します。
ポイントとして変換対象となるクラスに DataContract を付与します。
また、変換対象となるメンバーに DataMember を付与します。
JSONのキー名は通常小文字になるかと思いますので、Name でキー名を設定します。
[DataContract]
public class SampleModel
{
[DataMember(Name = "intValue")]
public int IntValue { get; set; }
[DataMember(Name = "stringValue")]
public string StringValue { get; set; }
[DataMember(Name = "dateTimeValue")]
public DateTime DateTimeValue { get; set; }
[DataMember(Name = "listValue")]
public List<string> ListtValue { get; set; }
[DataMember(Name = "mapValue")]
public Dictionary<string, string> MapValue { get; set; }
[DataMember(Name = "subSampleModel")]
public SubSampleModel SubSampleModel { get; set; }
}
public class SubSampleModel
{
[DataMember(Name = "intValue")]
public int IntValue { get; set; }
[DataMember(Name = "stringValue")]
public string StringValue { get; set; }
}
データの変換には System.Runtime.Serialization.Json の DataContractJsonSerializer を利用します。
var settings = new DataContractJsonSerializerSettings
{
UseSimpleDictionaryFormat = true,
DateTimeFormat = new DateTimeFormat("yyyy-MM-dd'T'HH:mm:ss.fff'Z'"),
};
var model = new SampleModel
{
IntValue = 10,
StringValue = "ABC",
DateTimeValue = DateTime.Now,
ListtValue = new List<string> { "First", "Second", "Third" },
MapValue = new Dictionary<string, string>() { { "Key01", "Val01" }, { "Key02", "Val02" } },
SubSampleModel = new SubSampleModel { IntValue = 20, StringValue = "DEF" }
};
using (MemoryStream ms = new MemoryStream())
{
var serializer = new DataContractJsonSerializer(typeof(SampleModel), settings);
serializer.WriteObject(ms, model);
Console.WriteLine(Encoding.UTF8.GetString(ms.ToArray()));
}
DataContractJsonSerializerSettings の UseSimpleDictionaryFormat = true とすることで、
Dictionary を キー : 値 の形式で出力する事が出来ます。
また、DateTimeFormat を設定することで日時フォーマットの出力形式を変更する事ができます。
{
"dateTimeValue": "2019-08-20T00:32:57.420Z",
"intValue": 10,
"listValue": [
"First",
"Second",
"Third"
],
"mapValue": {
"Key01": "Val01",
"Key02": "Val02"
},
"stringValue": "ABC",
"subSampleModel": {
"intValue": 20,
"stringValue": "DEF"
}
}