JavaScriptConverter Classe

Definizione

Fornisce una classe di base astratta per un convertitore di tipi personalizzato.

public ref class JavaScriptConverter abstract
public abstract class JavaScriptConverter
type JavaScriptConverter = class
Public MustInherit Class JavaScriptConverter
Ereditarietà
JavaScriptConverter

Esempio

Nell'esempio seguente viene illustrato come creare un convertitore personalizzato per la ListItemCollection classe.

using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Web.UI.WebControls;
using System.Collections;

namespace System.Web.Script.Serialization.CS
{
    public class ListItemCollectionConverter : JavaScriptConverter
    {

        public override IEnumerable<Type> SupportedTypes
        {
            //Define the ListItemCollection as a supported type.
            get { return new ReadOnlyCollection<Type>(new List<Type>(new Type[] { typeof(ListItemCollection) })); }
        }

        public override IDictionary<string, object> Serialize(object obj, JavaScriptSerializer serializer)
        {
            ListItemCollection listType = obj as ListItemCollection;

            if (listType != null)
            {
                // Create the representation.
                Dictionary<string, object> result = new Dictionary<string, object>();
                ArrayList itemsList = new ArrayList();
                foreach (ListItem item in listType)
                {
                    //Add each entry to the dictionary.
                    Dictionary<string, object> listDict = new Dictionary<string, object>();
                    listDict.Add("Value", item.Value);
                    listDict.Add("Text", item.Text);
                    itemsList.Add(listDict);
                }
                result["List"] = itemsList;

                return result;
            }
            return new Dictionary<string, object>();
        }

        public override object Deserialize(IDictionary<string, object> dictionary, Type type, JavaScriptSerializer serializer)
        {
            if (dictionary == null)
                throw new ArgumentNullException("dictionary");

            if (type == typeof(ListItemCollection))
            {
                // Create the instance to deserialize into.
                ListItemCollection list = new ListItemCollection();

                // Deserialize the ListItemCollection's items.
                ArrayList itemsList = (ArrayList)dictionary["List"];
                for (int i=0; i<itemsList.Count; i++)
                    list.Add(serializer.ConvertToType<ListItem>(itemsList[i]));

                return list;
            }
            return null;
        }
    }
}
Imports System.Collections.Generic
Imports System.Collections.ObjectModel
Imports System.Web.UI.WebControls
Imports System.Collections

Namespace System.Web.Script.Serialization.VB

    Public Class ListItemCollectionConverter
        Inherits JavaScriptConverter

        Public Overrides ReadOnly Property SupportedTypes() As _
            System.Collections.Generic.IEnumerable(Of System.Type)
            Get
                ' Define the ListItemCollection as a supported type.
                Return New ReadOnlyCollection(Of Type)(New List(Of Type) _
                (New Type() {GetType(ListItemCollection)}))
            End Get
        End Property

        Public Overrides Function Serialize(ByVal obj As Object, _
            ByVal serializer As JavaScriptSerializer) As _
            System.Collections.Generic.IDictionary(Of String, Object)

            Dim listType As ListItemCollection = CType(obj, ListItemCollection)

            If Not (listType Is Nothing) Then

                ' Create the representation.
                Dim result As New Dictionary(Of String, Object)

                Dim itemsList As New ArrayList()
                Dim item As ListItem
                For Each item In listType
                    ' Add each entry to the dictionary.
                    Dim listDict As New Dictionary(Of String, Object)
                    listDict.Add("Value", item.Value)
                    listDict.Add("Text", item.Text)
                    itemsList.Add(listDict)
                Next item
                result("List") = itemsList

                Return result
            End If
            Return New Dictionary(Of String, Object)
        End Function

        Public Overrides Function Deserialize(ByVal dictionary As _
            System.Collections.Generic.IDictionary(Of String, Object), _
            ByVal type As System.Type, ByVal serializer As JavaScriptSerializer) As Object

            If dictionary Is Nothing Then
                Throw New ArgumentNullException("dictionary")
            End If

            If type Is GetType(ListItemCollection) Then
                ' Create the instance to deserialize into.
                Dim list As New ListItemCollection()

                ' Deserialize the ListItemCollection's items.
                Dim itemsList As ArrayList = CType(dictionary("List"), ArrayList)
                Dim i As Integer
                For i = 0 To itemsList.Count - 1
                    list.Add(serializer.ConvertToType(Of ListItem)(itemsList(i)))
                Next i

                Return list
            End If

            Return Nothing

        End Function
    End Class
End Namespace

Commenti

La JavaScriptConverter classe consente di implementare processi di serializzazione e deserializzazione per i tipi gestiti che non sono supportati in modo nativo dalla JavaScriptSerializer classe. È anche possibile usare JavaScriptConverter quando è necessario un maggiore controllo sul processo di serializzazione e deserializzazione.

La SupportedTypes proprietà indica i tipi per i quali un convertitore personalizzato fornisce servizi di convertitore.

Per indicare che un convertitore personalizzato deve essere usato dall'istanza, è necessario registrare il convertitore con l'istanza JavaScriptSerializer . Se si usa direttamente la JavaScriptSerializer classe, è necessario usare il RegisterConverters metodo per registrare il convertitore. In caso contrario, se si richiamano metodi Web da ECMAScript (JavaScript) e si vuole usare il convertitore personalizzato, è possibile registrarlo aggiungendo un converters elemento nel file di configurazione. Per altre informazioni, vedere Procedura: Configurare i servizi di ASP.NET in Microsoft Ajax.

Quando l'istanza JavaScriptSerializer serializza un tipo per cui ha un convertitore personalizzato registrato, il serializzatore chiama il Serialize metodo . Analogamente, quando l'istanza esegue la JavaScriptSerializer deserializzazione di una stringa JSON (JavaScript Object Notation) e riconosce che un tipo all'interno della stringa JSON ha un convertitore personalizzato associato a esso, il serializzatore chiama il Deserialize metodo.

Note per gli implementatori

Quando si eredita da JavaScriptConverter, è necessario eseguire l'override dei membri seguenti:

Costruttori

JavaScriptConverter()

Inizializza una nuova istanza della classe JavaScriptConverter.

Proprietà

SupportedTypes

Se sottoposto a override in una classe derivata, ottiene un insieme dei tipi supportati.

Metodi

Deserialize(IDictionary<String,Object>, Type, JavaScriptSerializer)

Se sottoposto a override in una classe derivata, converte il dizionario fornito in un oggetto del tipo specificato.

Equals(Object)

Determina se l'oggetto specificato è uguale all'oggetto corrente.

(Ereditato da Object)
GetHashCode()

Funge da funzione hash predefinita.

(Ereditato da Object)
GetType()

Ottiene l'oggetto Type dell'istanza corrente.

(Ereditato da Object)
MemberwiseClone()

Crea una copia superficiale dell'oggetto Object corrente.

(Ereditato da Object)
Serialize(Object, JavaScriptSerializer)

Se sottoposto a override in una classe derivata, compila un dizionario di coppie nome/valore.

ToString()

Restituisce una stringa che rappresenta l'oggetto corrente.

(Ereditato da Object)

Si applica a

Vedi anche