|
分類:[VB.NET/VB2005 以降]
VB.NET Framework 4.7.2 Winform Win10
REST APIから取得したjson文字列を、整形し、エスケープ済みの文字列にしたいです。
' 文字列これを...
'{"value":[{"Data1":"AIUEO","Data2":"\u3042\u3044\u3046\u3048\u304A","Data3":"12345"},{"Data1":"Value","Data2":"!\u0022#$%\u0026\u0027()-=^~\\\\|@{\u002B*}\u003C\u003E?_","Data3":"ABCDEF"}]}
' 文字列こんな感じにしたい
'{
' "value": [
' {
' "Data1": "AIUEO",
' "Data2": "あいうえお"
' "Data3": "12345"
' },
' {
' "Data1": "Value",
' "Data2": "!\"#$%&'()-=^~\\\\|@{+*}<>?_"
' "Data3": "ABCDEF"
' }
' ]
'}
よろしくお願いいたします。
-----
Imports System.Text.Json
Public Class clsItem
Public Property Data1 As String
Public Property Data2 As String
End Class
Public Class clsList
Public Property value As New List(Of clsItem)
End Class
Sub Main()
Dim list = New clsList()
list.value.Add(New clsItem() With {.Data1 = "AIUEO", .Data2 = "あいうえお"})
list.value.Add(New clsItem() With {.Data1 = "Value", .Data2 = "!""#$%&'()-=^~\\|@{+*}<>?_"})
Dim jsonSiriOpt = New JsonSerializerOptions()
Dim jsonSiriStr As String = JsonSerializer.Serialize(list, jsonSiriOpt)
Console.WriteLine(jsonSiriStr)
'{"value":[{"Data1":"AIUEO","Data2":"\u3042\u3044\u3046\u3048\u304A"},{"Data1":"Value","Data2":"!\u0022#$%\u0026\u0027()-=^~\\\\|@{\u002B*}\u003C\u003E?_"}]}
' ↓Data3プロパティありの時...
'{"value":[{"Data1":"AIUEO","Data2":"\u3042\u3044\u3046\u3048\u304A","Data3":"12345"},{"Data1":"Value","Data2":"!\u0022#$%\u0026\u0027()-=^~\\\\|@{\u002B*}\u003C\u003E?_","Data3":"ABCDEF"}]}
Dim jsonDeseOpt = New JsonSerializerOptions()
Dim jsonDeseObj = JsonSerializer.Deserialize(Of clsList)(jsonSiriStr, jsonDeseOpt)
For Each Item In jsonDeseObj.value
Console.WriteLine($"Data1={Item.Data1} Data2={Item.Data2}")
Next
'Data1=AIUEO Data2=あいうえお
'Data1=Value Data2=!"#$%&'()-=^~\\|@{+*}<>?_
' こんな感じにしたい
'{
' "value": [
' {
' "Data1": "AIUEO",
' "Data2": "あいうえお"
' "Data3": "12345"
' },
' {
' "Data1": "Value",
' "Data2": "!\"#$%&'()-=^~\\\\|@{+*}<>?_"
' "Data3": "ABCDEF"
' }
' ]
'}
'*************
' オブジェクト化しても良いが、取りこぼしがなければ(Data3があれば)OK
Dim jsonOpt = New JsonSerializerOptions()
jsonOpt.Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping
jsonOpt.WriteIndented = True
Dim jsonStr As String = JsonSerializer.Serialize(list, jsonOpt)
Console.WriteLine(jsonStr)
'{
' "value": [
' {
' "Data1": "AIUEO",
' "Data2": "あいうえお"
' },
' {
' "Data1": "Value",
' "Data2": "!\"#$%&'()-=^~\\\\|@{+*}<>?_"
' }
' ]
'}
End Sub
|