This post is a continuation of previous post serialization.
In particular we will see that the SOAP and JSON serialization.
Serialization SOAP SOAP serialization is committed to the SoapFormatter System.Runtime.Serialization.Formatters.Soap contained in the namespace in the library of the same name. The SOAP formatter
goes back to the earliest versions of the framework and, unfortunately, from a certain point, even though it was declared obsolete, it was not brought forward in the development and does not support certain types of data very much used in the world. NET such as generics and nullable.
For this reason, we can not serialize in SOAP format (using the SoapFormatter) our bill (see previous post) as this has a property of type List (Of DettagliFattura) (generic).
JSON serialization format JSON serialization (more info here ) is a textual format very popular in AJAX applications. Entry is a way to serialize complex objects even with a very compact size and easy to interoperate with JavaScript, therefore, well suited for scenarios partoicolarmente AJAX-style web.
JSON serialization can be done using the class DataContractJsonSerializer that framework 4.0 is contained in the namespace System.Runtime.Serialization.Json all’interno dell’omonimo assembly.
Fate attenzione perchè, se state sviluppando per il framework 3.5 (prima di questo la classe DataContractJsonSerialization non era presente), trovate la classe nello stesso namespace ma l’assembly è System.ServiceModel.Web.
La classe DataContractJsonSerializer prevede, tra i vari metodi, WriteObject e ReadObject che permettono , rispettivamente, di serializzare e deserializzare un’oggetto in formato JSON.
Entrambi i metodi sfruttano uno stream per serializzare l’oggetto. In base alle nostre esigenze tale stream potrebbe essere in memoria (come nell’esempio riportato in seguito), su file o su un canale web (ad esempio come response to a request from a remote client).
methods for serialization and deserialization of the object are Invoice:
- Public Shared Function SerializzaJSON (ByVal bill As Invoice ) As String
- If bill Is Nothing Then Throw New ArgumentNullException ( "Bill" )
-      Dim strJSON As String = Nothing
-      Dim serializer = New DataContractJsonSerializer ( GetType ( Fattura ))
-      Using memStream = New MemoryStream ()
-          serializer .WriteObject(memStream, fattura)
-         strJSON = Encoding.Default.GetString( memStream .ToArray())
-      End Using
-      Return strJSON
- End Function
-
- Public Shared Function DeserializzaJSON( ByVal As strFattura String) As Invoice
- Dim retObj As Invoice = Nothing
- & # 160; Dim serializer = New DataContractJsonSerializer ( GetType ( Invoice )) &
- # 160; Using memStream = New MemoryStream (Encoding.Default.GetBytes (strFattura))
- retObj = CType (serializer . ReadObject (memStream) Invoice )
- End Using Return
- retObj
- End Function
The result is as follows:
We observe that, in the examples, we used the default encoding for strings. Evidently, if necessary, the encoding may be the one we want.
If our class (as in Bill) is composed of objects. NET serializable, we can immediately use the JSON serialization.
Alternatively, we can decorate our class (and all those that may be used as a property) with the Serializable attribute or the attribute DataContract.
In the first case it is enough to decorate the sun and JSON serialization classes will have the properties expressed by the name of the attribute that is encapsulated by private property. In the case of property definite in modo compatto (come accade nella Fattura) il compilatore crea, dietro le quinte un attributo per ogni proprietà con lo stesso nome della proprietà a cui viene anteposto il carattere “_”. In questo caso il JSON risultante vedrà le proprietà espresse con il nome della proprietà preceduta da “_”.
Nel caso dell’attributo DataContract, invece, è necessario decorare anche ogni proprietà con l’attributo DataMember (se una proprietà non viene decorata con DataMember, questa non finisce nella serializzazione).
L’attributo DataMember permette di rinominare la proprietà all’interno del JSON risultante:
- \u0026lt; DataMember (Name: = "numeroDocumento" )>
- Public Property NumeroDocumento As String
In this case, the properties, the ' inside of the JSON, will be called "numeroDocumento" and not "NumeroDocumento.
using DataContract and DataMember we can intervene in the resulting JSON in order to customize the results to our liking (especially useful when we are given the path and we must re-create the class).
Serializzazion custom
Just a hint at the possibility of creating a custom serialization of objects.
To do this, the framework provides us with the interface that has two IFormatter Serialize and Deserialize methods that we have to redefine our logic by implementing the serialization / deserialization:
An example might be:
- Imports System.Runtime.Serialization
- Public Class MioSerializzatore
- Implements IFormatter
-
-      Public Property Binder As System.Runtime.Serialization. SerializationBinder Implements System.Runtime.Serialization. IFormatter .Binder
-          Get
-
-          End Get
-          Set ( ByVal value As System.Runtime.Serialization. SerializationBinder )
-
-          End Set
-      End Property
-
-      Public Property Context As System.Runtime.Serialization. StreamingContext Implements System.Runtime.Serialization. IFormatter .Context
-          Get
-
-          End Get
-          Set ( ByVal value As System.Runtime.Serialization. StreamingContext )
-
-          End Set
-      End Property
-
-      Public Function Deserialize( ByVal serializationStream As System.IO. Stream ) As Object Implements System.Runtime.Serialization. IFormatter . Deserialize
- 'Here comes the logic of deserialization
- End Function
- Public Sub Serialize (ByVal serializationStream As System.IO. Stream , ByVal graph As Object ) Implements System.Runtime.Serialization. IFormatter .Serialize
-          ' qui ci va la logica di serializzazione
-      End Sub
-
-      Public Property SurrogateSelector As System.Runtime.Serialization. ISurrogateSelector Implements System.Runtime.Serialization. IFormatter .SurrogateSelector
-          Get
-
-          End Get
-          Set ( ByVal value As System.Runtime.Serialization. ISurrogateSelector )
- End September
- End Property End
- Class
0 comments:
Post a Comment