Export (0) Print
Expand All

JavaScriptSerializer.ConvertToType<T> Method (Object)

Converts the given object to the specified type.

Namespace:  System.Web.Script.Serialization
Assembly:  System.Web.Extensions (in System.Web.Extensions.dll)

public T ConvertToType<T>(
	Object obj
)

Type Parameters

T

The type to which obj will be converted.

Parameters

obj
Type: System.Object

The object to convert.

Return Value

Type: T
The object that has been converted to the target type.

ExceptionCondition
InvalidOperationException

obj (or a nested member of obj) contains a "__type" property that indicates a custom type, but the type resolver that is associated with the serializer cannot find a corresponding managed type.

-or-

obj (or a nested member of obj) contains a "__type" property that indicates a custom type, but the result of deserializing the corresponding JSON string cannot be assigned to the expected target type.

-or-

obj (or a nested member of obj) contains a "__type" property that indicates either Object or a non-instantiable type (for example, an abstract type or an interface).

-or-

An attempt was made to convert obj to an array-like managed type, which is not supported for use as a deserialization target.

-or-

It is not possible to convert obj to T.

ArgumentException

obj is a dictionary type and a non-string key value was encountered.

-or-

obj includes member definitions that are not available on type T.

The ConvertToType method tries to convert the object instance that is represented by obj to an instance of type T. During this conversion there is no guarantee that object reference equality is maintained. Therefore, you cannot assume that obj and T refer to the same object.

ConvertToType is intended to be used if you implement a class that derives from JavaScriptConverter. Converter code must be able to take a value that is in the dictionary that the serializer passes to it, and then convert that value to an instance of type T. Instead of re-implementing the custom conversion code to perform this task, you can call the ConvertToType method from the converter code.

The following example shows how to use the ConvertToType method to obtain a ListItem object from a value in the dictionary that is passed to the converter. This code example is part of a larger example provided for the JavaScriptSerializer class.

ArrayList itemsList = (ArrayList)dictionary["List"];
for (int i=0; i<itemsList.Count; i++)
    list.Add(serializer.ConvertToType<ListItem>(itemsList[i]));

.NET Framework

Supported in: 4.5, 4, 3.5

Windows 8.1, Windows Server 2012 R2, Windows 8, Windows Server 2012, Windows 7, Windows Vista SP2, Windows Server 2008 (Server Core Role not supported), Windows Server 2008 R2 (Server Core Role supported with SP1 or later; Itanium not supported)

The .NET Framework does not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.

Show:
© 2014 Microsoft