|
■No79709 (やんまー さん) に返信
[{"ID1":111,"ID2":222}] が何を意味するか分かりますか?
ID1, ID2 というメンバーを持つオブジェクトの配列ですよね。(この例では配列の要素
数は 1 ですが)
とすると、そのオブジェクトのクラス定義を追加し(仮に ChildID クラスとします)、
親の Person クラスの Id は追加したクラス定義の List(Of ChildID) を指すように定義
し直せばいいと思います。
具体的には以下のような感じ:
Option Strict On
Imports System.Runtime.Serialization
Imports System.Runtime.Serialization.Json
Imports System.Collections.Generic
Imports System.IO
Imports System.Text
Module Module1
Sub Main()
Dim p As New Person
p.Name = "徳川家康"
p.Id = New List(Of ChildId)
p.Id.Add(New ChildId With {.ID1 = 111, .ID2 = 222})
Dim json As String
Using stream As New MemoryStream
Dim serializer As New DataContractJsonSerializer(p.GetType)
serializer.WriteObject(stream, p)
stream.Position = 0
Using reader As New StreamReader(stream)
json = reader.ReadToEnd
Console.WriteLine(json)
End Using
End Using
Console.WriteLine("---------------------------------------------------")
Using stream As New MemoryStream(Encoding.Unicode.GetBytes(json))
Dim serializer As New DataContractJsonSerializer(p.GetType)
Dim p2 As Person = DirectCast(serializer.ReadObject(stream), Person)
Console.WriteLine("Name: {0}", p2.Name)
For Each childId As ChildId In p2.Id
Console.WriteLine("ID1: {0}, ID2: {1}", childId.ID1, childId.ID2)
Next
End Using
End Sub
' 結果は:
' {"Id":[{"ID1":111,"ID2":222}],"Name":"徳川家康"}
' ---------------------------------------------------
' Name: 徳川家康
' ID1: 111, ID2: 222
End Module
<DataContract()>
Public Class Person
<DataMember()>
Public Property Id As List(Of ChildId)
<DataMember()>
Public Property Name As String
End Class
<DataContract()>
Public Class ChildId
<DataMember()>
Public Property ID1 As Integer
<DataMember()>
Public Property ID2 As Integer
End Class
|