5
5

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 5 years have passed since last update.

設定ファイル(App.config)でJSONを使うには

Posted at

キー1つで複数の値をまとめて扱う

JSONのフォーマットやエスケープについては以下が分かりやすい。
JSONについて

XMLのエスケープは以下。
XMLエスケープ文字

<appSettings>のセクションでは基本的には1つのキーに対し値を1つしか設定できない。
でも、関連する値をJSONでまとめて設定できると楽かもしれない。

環境

  • Visual Studio Express 2013
  • Visual Basic
  • .NET Framework 4.5

Json.NETが便利らしいけど、今回は特に使用せず。

App.config の設定

  • <add key="abc" value='xyz' />みたいにvalueの値をシングルクォートで囲うとJSONにダブルクォートがそのまま使えるのでちょっとだけ見やすくなる。
  • 設定値にシングルクォートやダブルクォートがある時はエスケープすれば使用が可能。
  • あと、適切な設定値が思いつかなかったのでデータはテキトー。
app.config
<configuration>
  <appSettings>    
    <add key="json" value='
      {
        "Employees": [
          {"Id": 1, "Name": "John Doe", "Greeting": "alert(&apos;Hello, world!&apos;);"},
          {"Id": 2, "Name": "Anna Smith", "Greeting": "&lt;strong&gt;Hello, world!&lt;/strong&gt;"},
          {"Id": 3, "Name": "Peter Jones", "Greeting": "print(\"Hello, world!\")"},
          {"Id": 4, "Name": "Tyler Durden", "Greeting": null}      
        ]
      }
    ' />
  </appSettings>
</configuration>

サンプルソース

以下の参照設定を追加する。

  • System.Configuration.dll
  • System.ServiceModel.Web.dll
Form1.vb
Imports System.Configuration
Imports System.ServiceModel.Dispatcher
Public Class Form1

    Public Class Employee
        Public Property Id As Integer
        Public Property Name As String
        Public Property Greeting As String
    End Class

    Public Class Company
        Public Employees As List(Of Employee)
    End Class

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click

        ' 設定ファイルから値を取得
        Dim json As String = ConfigurationManager.AppSettings("json")

        Dim jsonQuery As New JsonQueryStringConverter()

        Dim com As Company = jsonQuery.ConvertStringToValue(json, GetType(Company))

        For Each emp As Employee In com.Employees
            Console.WriteLine(String.Format("ID:{0},Name:{1},Greeting:{2}", _
                                            emp.Id.ToString(), _
                                            emp.Name, _
                                            emp.Greeting))
        Next

        com = Nothing
        jsonQuery = Nothing


    End Sub

End Class

実行結果

ID:1,Name:John Doe,Greeting:alert('Hello, world!');
ID:2,Name:Anna Smith,Greeting:<strong>Hello, world!</strong>
ID:3,Name:Peter Jones,Greeting:print("Hello, world!")
ID:4,Name:Tyler Durden,Greeting:
5
5
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
5
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?