Serializzare gli oggetti con il formato del ViewState
Scritto da
Massimo Bonanni il
venerdì 10 giugno 2011
•
Linguaggio:
• Livello: 100
La seguente classe consente di
serializzare/deserializzare un oggetto in formato
JSON.
VB.NET
Imports System.Runtime.Serialization.Json
Imports System.IO
Imports System.Text
Public NotInheritable Class SerializzatoreJSON(Of T As New)
Private Sub New()
End Sub
Public Shared Function Serializza(ByVal oggetto As T) As String
If oggetto Is Nothing Then Throw New ArgumentNullException("Oggetto non può essere null")
Dim strJSON As String = Nothing
Dim serializer = New DataContractJsonSerializer(GetType(T))
Using memStream = New MemoryStream()
serializer.WriteObject(memStream, oggetto)
strJSON = Encoding.Default.GetString(memStream.ToArray())
End Using
Return strJSON
End Function
Public Shared Function Deserializza(ByVal strOggetto As String) As T
Dim retObj As T
Dim serializer = New DataContractJsonSerializer(GetType(T))
Using memStream = New MemoryStream(Encoding.Default.GetBytes(strOggetto))
retObj = CType(serializer.ReadObject(memStream), T)
End Using
Return retObj
End Function
End Class
C#
public sealed class SerializzatoreJSON<T>
where T : new()
{
private SerializzatoreJSON()
{
}
public static string Serializza(T oggetto)
{
if (oggetto == null) throw new ArgumentNullException("Oggetto non può essere null");
string strJSON = null;
DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T));
using (MemoryStream memStream = new MemoryStream())
{
serializer.WriteObject(memStream, oggetto);
strJSON = Encoding.Default.GetString(memStream.ToArray());
}
return strJSON;
}
public static T Deserializza(string strOggetto)
{
T retObj;
DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T));
using (MemoryStream memStream = new MemoryStream(Encoding.Default.GetBytes(strOggetto)))
{
retObj = (T)serializer.ReadObject(memStream);
}
return retObj;
}
}
La classe DataContractJsonSerializer si trova nell'assembly
System.Runtime.Serialization nel caso in cui si stia lavorando con
il framework 4.0 mentre si trova nell'assembly
System.ServiceModel.Web se si lavora con il framewor 3.5.
Tags: JSON