JSON形式でクラスをシリアライズ・デシリアライズする - C#

JSON形式でクラスをシリアライズ、デシリアライズするコードを紹介します。

概要

JSON形式でクラスをシリアライズ、デシリアライズする場合には、DataContractJsonSerializer クラスを利用します。
シリアライズする場合には、DataContractJsonSerializer オブジェクトのWriteObject() メソッドを利用します。 デシリアライズする倍には、DataContractJsonSerializer オブジェクトのReadObject() メソッドを利用します。
補足
XML形式でのクラスのシリアライズ、デシリアライズはこちらの記事を参照してください。

プログラム

プロジェクト設定

新規のWindowsフォームアプリケーションプロジェクトを作成します。アセンブリの参照に、System.Runtime.Serializationを追加します。

UI

下図のフォームをデザインします。


コントロール名は以下の通りです。
  • ID欄のテキストボックス: textBox_ID
  • Name欄のテキストボックス: textBox_Name
  • Output欄のテキストボックス: textBox_Output
  • Serializeボタン: button1
  • DeSerializeボタン: button2
  • Clearボタン: button3

コード

以下のコードを実装します。
InfoClass.cs (情報格納クラスのコード)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.Serialization;

namespace JsonSerializeDemo
{
  [System.Runtime.Serialization.DataContract]
  class InfoClass
  {
    [System.Runtime.Serialization.DataMember()]
    public int ID { get; set; }
    [System.Runtime.Serialization.DataMember()]
    public string Name { get; set; }

  }
}

解説

using System.Runtime.Serialization.Json;
を追加し、シリアライズのクラスを参照できるようにします。プロジェクトの[参照設定]にもSystem.Runtime.Serializationアセンブリの参照を追加します。

シリアライズするクラス(InfoClass)に
[System.Runtime.Serialization.DataContract]
を記述しDataContract属性を付与します。

また、クラスのプロパティに
[System.Runtime.Serialization.DataMember()]
を記述し、DataMember属性を付与します。

FormMain.cs (メインフォームクラスのコード)
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Runtime.Serialization.Json;

namespace JsonSerializeDemo
{
  public partial class FormMain : Form
  {
    public FormMain()
    {
      InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
      DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(InfoClass));

      InfoClass infoc = new InfoClass();
      infoc.ID = Convert.ToInt32(textBox_ID.Text);
      infoc.Name = textBox_Name.Text;

      MemoryStream ms = new MemoryStream();
      serializer.WriteObject(ms, infoc);
      string JsonString = Encoding.UTF8.GetString(ms.ToArray());

      textBox_Output.Text = JsonString;

    }

    private void button2_Click(object sender, EventArgs e)
    {
      DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(InfoClass));
      
      byte[] bytes = Encoding.UTF8.GetBytes(textBox_Output.Text);
      MemoryStream ms = new MemoryStream(bytes);
      InfoClass infoc = (InfoClass)serializer.ReadObject(ms);

      textBox_ID.Text = Convert.ToString(infoc.ID);
      textBox_Name.Text = infoc.Name;
    }

    private void button3_Click(object sender, EventArgs e)
    {
      textBox_ID.Text = "";
      textBox_Name.Text = "";
    }
  }
}

解説

using節に下記コードを追加し、シリアライズのクラスを参照できるようにします。プロジェクトの[参照設定]にもSystem.Runtime.Serializationアセンブリの参照を追加します。
using System.Runtime.Serialization.Json;

下記のコードにてシリアライザのインスタンスを作成します。
DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(InfoClass));

下記コードにて、情報格納クラスのインスタンスを作成しメンバ(プロパティ)に値を代入します。
InfoClass infoc = new InfoClass();
infoc.ID = Convert.ToInt32(textBox_ID.Text);
infoc.Name = textBox_Name.Text;

下記コードにて、シリアライズした情報を格納するメモリストリームを準備します。
MemoryStream ms = new MemoryStream();

シリアライザーのWriteObjectメソッドを用いてシリアライズします。シリアライズされたデータは先に準備したメモリストリームに書き込まれます。
serializer.WriteObject(ms, infoc);

メモリストリームからデータを読み出しUTF8にエンコードして文字列を取得します。
string JsonString = Encoding.UTF8.GetString(ms.ToArray());

実行結果

アプリケーションを実行し、Serializeボタンを押すと下図の画面のようにJSON形式でシリアライズされたクラス情報がテキストボックスに表示されます。
クラスの情報をJSON形式でシリアライズしOutputのテキストボックスに表示されていることがわかります。


Clearボタンを押しID,NameテキストボックスをクリアしたのちDeSerializeボタンを押すと、JSONの内容からクラスのインスタンスを作成しメンバ(プロパティに)格納された値を画面に表示できます。

このページのキーワード
  • C#
  • JSON
  • クラスオブジェクトのシリアライズ
  • クラスオブジェクトのデシリアライズ
著者
iPentecのメインプログラマー
C#, ASP.NET の開発がメイン、少し前まではDelphiを愛用
最終更新日: 2021-08-25
作成日: 2011-03-24
iPentec all rights reserverd.