|
VB.NET / C# Create JSON (DataContractJsonSerializer) Serialize and Deserialize เชื่อว่าหลาย ๆ คนที่ใช้ .NET ในการเขียนแกรม คงจะมีปัญหาเรื่องการสร้างไฟล์ JSON และอ่านไฟล์ JSON ว่าจะใช้ ตัวไหนดี ซึ่งใน .NET ก็จะมี Library ให้เลือกใช้มากมาย ที่เป็นของฟรี แต่ในบทความนี้ผมจะแนะนำให้ใช้ Library ที่มีอยู่ใน .NET ที่สามารถเรียกใช้งานได้ง่าย เราจะใช้ NameSpace ของ System.Runtime.Serialization และจะมีตัวอย่างทั้ง VB.NET และ C#
ในกรณีที่ใช้ Library ที่มีอยู่ใน .NET Framework ให้ Add Reference ต่าง ๆ เหล่านี้

เลือก System.Servicemodel.Web และ System.Xml.Linq

Add ตัวนี้เข้ามา System.Runtime.Serialization
ให้ Code ของ VB.NET และ C# ให้ Import / using ตัวนี้เข้าไป
System.Runtime.Serialization
System.Runtime.Serialization.Json
System.Collections.ObjectModel
System.IO
Code for C#
การสร้าง Create JSON (Serialize)
1. การสร้าง JSON แบบข้อมูล Array ชุดเดียว
public class myName
{
public string Name { get; set; }
public string Surname { get; set; }
}
protected void Page_Load(object sender, EventArgs e)
{
List<myName> nameList = new List<myName>();
myName name = new myName();
name.Name = "Weerachai";
name.Surname = "Nukitram";
nameList.Add(name);
MemoryStream str = new MemoryStream();
DataContractJsonSerializer ser = new DataContractJsonSerializer(nameList.GetType());
ser.WriteObject(str, nameList);
str.Position = 0;
StreamReader sr = new StreamReader(str);
this.lbDisplay.Text = sr.ReadToEnd();
}
Result
[{"Name":"Weerachai","Surname":"Nukitram"}]

2. การสร้าง JSON แบบข้อมูล Array มากกว่า 1 ชุด
public class myName
{
public string Name { get; set; }
public string Surname { get; set; }
}
protected void Page_Load(object sender, EventArgs e)
{
List<myName> nameList = new List<myName>();
myName name = new myName();
name.Name = "Weerachai";
name.Surname = "Nukitram";
nameList.Add(name);
name = new myName();
name.Name = "Adisorn";
name.Surname = "Bunsong";
nameList.Add(name);
MemoryStream str = new MemoryStream();
DataContractJsonSerializer ser = new DataContractJsonSerializer(nameList.GetType());
ser.WriteObject(str, nameList);
str.Position = 0;
StreamReader sr = new StreamReader(str);
this.lbDisplay.Text = sr.ReadToEnd();
}
Result
[{"Name":"Weerachai","Surname":"Nukitram"},{"Name":"Adisorn","Surname":"Bunsong"}]
การอ่าน Read JSON (Deserialize)
1. การอ่าน JSON แบบข้อมูล Array ชุดเดียว
JSON
{"Name":"Weerachai","Surname":"Nukitram"}
public class myName
{
public string Name { get; set; }
public string Surname { get; set; }
}
protected void Page_Load(object sender, EventArgs e)
{
string strJSON = null;
// JSON = {"Name":"Weerachai","Surname":"Nukitram"}
strJSON = " {\"Name\":\"Weerachai\",\"Surname\":\"Nukitram\"}";
myName name = ReadToObject(strJSON);
Console.WriteLine("Name : " + name.Name.ToString());
Console.WriteLine("Surname : " + name.Surname.ToString());
}
public static myName ReadToObject(string json)
{
myName deserializedMember = new myName();
MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(json));
DataContractJsonSerializer ser = new DataContractJsonSerializer(deserializedMember.GetType());
deserializedMember = ser.ReadObject(ms) as myName;
ms.Close();
return deserializedMember;
}
Result
Name : Weerachai
Surname : Nukitram
2. การอ่าน JSON แบบข้อมูล Array หลายชุด
JSON
[{"Name":"Weerachai","Surname":"Nukitram"},{"Name":"Adisorn","Surname":"Bunsong"}]
public class myName
{
public string Name { get; set; }
public string Surname { get; set; }
}
protected void Page_Load(object sender, EventArgs e)
{
string strJSON = null;
// JSON = [{"Name":"Weerachai","Surname":"Nukitram"},{"Name":"Adisorn","Surname":"Bunsong"}]
strJSON = " [{\"Name\":\"Weerachai\",\"Surname\":\"Nukitram\"}, {\"Name\":\"Adisorn\",\"Surname\":\"Bunsong\"}]";
MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(strJSON));
ObservableCollection<myName> list = new ObservableCollection<myName>();
DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(ObservableCollection<myName>));
list = (ObservableCollection<myName>)serializer.ReadObject(ms);
foreach (myName name in list)
{
Console.WriteLine("Name : " + name.Name.ToString());
Console.WriteLine("Surname : " + name.Surname.ToString());
Console.WriteLine("======================");
}
}
Result
Name : Weerachai
Surname : Nukitram
======================
Name : Adisorn
Surname : Bunsong
Code for VB.NET
การสร้าง Create JSON (Serialize)
1. การสร้าง JSON แบบข้อมูล Array ชุดเดียว
Public Class myName
Public Property Name() As String
Get
Return m_Name
End Get
Set(value As String)
m_Name = value
End Set
End Property
Private m_Name As String
Public Property Surname() As String
Get
Return m_Surname
End Get
Set(value As String)
m_Surname = value
End Set
End Property
Private m_Surname As String
End Class
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim nameList As New List(Of myName)
Dim name As New myName()
name.Name = "Weerachai"
name.Surname = "Nukitram"
nameList.Add(name)
Dim str As New MemoryStream()
Dim ser As New DataContractJsonSerializer(nameList.GetType())
ser.WriteObject(str, nameList)
str.Position = 0
Dim sr As New StreamReader(str)
Me.lbDisplay.Text = sr.ReadToEnd()
End Sub
Result
[{"Name":"Weerachai","Surname":"Nukitram"}]
2. การสร้าง JSON แบบข้อมูล Array มากกว่า 1 ชุด
Public Class myName
Public Property Name() As String
Get
Return m_Name
End Get
Set(value As String)
m_Name = value
End Set
End Property
Private m_Name As String
Public Property Surname() As String
Get
Return m_Surname
End Get
Set(value As String)
m_Surname = value
End Set
End Property
Private m_Surname As String
End Class
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim nameList As New List(Of myName)
Dim name As New myName()
name.Name = "Weerachai"
name.Surname = "Nukitram"
nameList.Add(name)
name = New myName()
name.Name = "Adisorn"
name.Surname = "Bunsong"
nameList.Add(name)
Dim str As New MemoryStream()
Dim ser As New DataContractJsonSerializer(nameList.GetType())
ser.WriteObject(str, nameList)
str.Position = 0
Dim sr As New StreamReader(str)
Me.lbDisplay.Text = sr.ReadToEnd()
End Sub
Result
[{"Name":"Weerachai","Surname":"Nukitram"},{"Name":"Adisorn","Surname":"Bunsong"}]
การอ่าน Read JSON (Deserialize)
1. การอ่าน JSON แบบข้อมูล Array ชุดเดียว
JSON
{"Name":"Weerachai","Surname":"Nukitram"}
Public Class myName
Public Property Name() As String
Get
Return m_Name
End Get
Set(value As String)
m_Name = value
End Set
End Property
Private m_Name As String
Public Property Surname() As String
Get
Return m_Surname
End Get
Set(value As String)
m_Surname = value
End Set
End Property
Private m_Surname As String
End Class
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim strJSON As String = Nothing
' JSON = {"Name":"Weerachai","Surname":"Nukitram"}
strJSON = " {""Name"":""Weerachai"",""Surname"":""Nukitram""}"
Dim name As myName = ReadToObject(strJSON)
Console.WriteLine("Name : " & name.Name.ToString())
Console.WriteLine("Surname : " & name.Surname.ToString())
End Sub
Public Shared Function ReadToObject(json As String) As myName
Dim deserializedMember As New myName()
Dim ms As New MemoryStream(Encoding.UTF8.GetBytes(json))
Dim ser As New DataContractJsonSerializer(deserializedMember.GetType())
deserializedMember = TryCast(ser.ReadObject(ms), myName)
ms.Close()
Return deserializedMember
End Function
Result
Name : Weerachai
Surname : Nukitram
2. การอ่าน JSON แบบข้อมูล Array หลายชุด
JSON
[{"Name":"Weerachai","Surname":"Nukitram"},{"Name":"Adisorn","Surname":"Bunsong"}]
Public Class myName
Public Property Name() As String
Get
Return m_Name
End Get
Set(value As String)
m_Name = value
End Set
End Property
Private m_Name As String
Public Property Surname() As String
Get
Return m_Surname
End Get
Set(value As String)
m_Surname = value
End Set
End Property
Private m_Surname As String
End Class
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim strJSON As String = Nothing
' JSON = [{"Name":"Weerachai","Surname":"Nukitram"},{"Name":"Adisorn","Surname":"Bunsong"}]
strJSON = " [{""Name"":""Weerachai"",""Surname"":""Nukitram""}, {""Name"":""Adisorn"",""Surname"":""Bunsong""}]"
Dim ms As New MemoryStream(Encoding.UTF8.GetBytes(strJSON))
Dim list As New ObservableCollection(Of myName)
Dim serializer As New DataContractJsonSerializer(GetType(ObservableCollection(Of myName)))
list = DirectCast(serializer.ReadObject(ms), ObservableCollection(Of myName))
For Each name As myName In list
Console.WriteLine("Name : " & name.Name.ToString())
Console.WriteLine("Surname : " & name.Surname.ToString())
Console.WriteLine("======================")
Next
End Sub
Result
Name : Weerachai
Surname : Nukitram
======================
Name : Adisorn
Surname : Bunsong
ตัวอย่างบทความที่มีการสร้าง .NET กับ JSON
Windows Phone and JSON
Windows Phone Get Retrieving Data from Web Server (PHP & MySQL and JSON)
|
|