0
0

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.

.NET Framework 3.5でクラスのプロパティをJSON出力する方法

Last updated at Posted at 2020-06-11

TL;DR

  • 本記事では、クラスのプロパティのJSON形式出力を自分で実装する場合のコードを記載します。

    • 最近の.NETであれば、json出力用のライブラリを利用することでクラスのプロパティをJSON形式で簡単に出力することが可能です。
    • 何らかの制限(Frameworkのバージョンが3.5以前、仕様ライブラリ制限等)がある場合に自力での実装が必要となります。

コード

InputParameter.vb
Imports System.Reflection

Public Class InputParameter
    Public Property ID1 As Integer
    Public Property Value1 As Short

    Public Overrides Function ToString() As String
        Dim strInfo As New System.Text.StringBuilder
        strInfo.Length = 0

        strInfo.Append("{")
        strInfo.Append(String.Format("""{0}""", Me.GetType().Name) & ":{")

        Dim strValue As New System.Text.StringBuilder
        strValue.Length = 0
        For Each p In Me.GetType().GetProperties
            If p.GetValue(Me, Nothing) Is Nothing Then
                strValue.Append(String.Format(",""{0}"": """"", p.Name))
            Else
                strValue.Append(String.Format(",""{0}"": ""{1}""", p.Name, p.GetValue(Me, Nothing)))
            End If
        Next
        strInfo.Append(Mid(strValue.ToString, 2))

        strInfo.Append("}")
        strInfo.Append("}")

        Return strInfo.ToString
    End Function
End Class
ToStringメソッドの出力結果(整形済み)
{
    "InputParameter": {
        "ID1": "11111",
        "Value1": "22222"
    }
}
0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?