Udostępnij za pośrednictwem


JavaScriptConverter Klasa

Definicja

Udostępnia abstrakcyjną klasę bazową dla konwertera typów niestandardowych.

public ref class JavaScriptConverter abstract
public abstract class JavaScriptConverter
type JavaScriptConverter = class
Public MustInherit Class JavaScriptConverter
Dziedziczenie
JavaScriptConverter

Przykłady

W poniższym przykładzie pokazano, jak utworzyć niestandardowy konwerter dla ListItemCollection klasy.

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

Uwagi

Klasa JavaScriptConverter umożliwia implementowanie procesów serializacji i deserializacji dla typów zarządzanych, które nie są natywnie obsługiwane przez klasę JavaScriptSerializer . Można również użyć JavaScriptConverter , gdy potrzebujesz większej kontroli nad procesem serializacji i deserializacji.

Właściwość SupportedTypes wskazuje typy, dla których konwerter niestandardowy udostępnia usługi konwertera.

Aby wskazać, że konwerter niestandardowy musi być używany przez JavaScriptSerializer wystąpienie, należy zarejestrować konwerter w wystąpieniu. Jeśli używasz JavaScriptSerializer klasy bezpośrednio, należy użyć RegisterConverters metody do zarejestrowania konwertera. W przeciwnym razie, jeśli wywołasz metody sieci Web z kodu ECMAScript (JavaScript) i chcesz użyć konwertera niestandardowego, możesz go zarejestrować, dodając converters element w pliku konfiguracji. Aby uzyskać więcej informacji, zobacz How to: Configure ASP.NET Services in Microsoft Ajax (Jak skonfigurować usługi ASP.NET w usłudze Microsoft Ajax).

Gdy JavaScriptSerializer wystąpienie serializuje typ, dla którego ma zarejestrowany konwerter niestandardowy, serializator wywołuje metodę Serialize . Podobnie, gdy JavaScriptSerializer wystąpienie deserializuje ciąg JavaScript Object Notation (JSON) i rozpoznaje, że typ wewnątrz ciągu JSON ma skojarzony z nim konwerter niestandardowy, serializator wywołuje metodę Deserialize .

Uwagi dotyczące implementowania

Po dziedziczeniu z JavaScriptConverterprogramu należy zastąpić następujące elementy członkowskie:

Konstruktory

JavaScriptConverter()

Inicjuje nowe wystąpienie klasy JavaScriptConverter.

Właściwości

SupportedTypes

Po zastąpieniu klasy pochodnej pobiera kolekcję obsługiwanych typów.

Metody

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

Po przesłonięciu w klasie pochodnej element konwertuje podany słownik na obiekt określonego typu.

Equals(Object)

Określa, czy dany obiekt jest taki sam, jak bieżący obiekt.

(Odziedziczone po Object)
GetHashCode()

Służy jako domyślna funkcja skrótu.

(Odziedziczone po Object)
GetType()

Type Pobiera wartość bieżącego wystąpienia.

(Odziedziczone po Object)
MemberwiseClone()

Tworzy płytkią kopię bieżącego Objectelementu .

(Odziedziczone po Object)
Serialize(Object, JavaScriptSerializer)

Po zastąpieniu w klasie pochodnej tworzy słownik par nazw/wartości.

ToString()

Zwraca ciąg reprezentujący bieżący obiekt.

(Odziedziczone po Object)

Dotyczy

Zobacz też