JavaScriptSerializer.ConvertToType Método
Definição
Sobrecargas
| ConvertToType(Object, Type) |
Converte o objeto especificado no tipo especificado.Converts the specified object to the specified type. |
| ConvertToType<T>(Object) |
Converte o objeto fornecido no tipo especificado.Converts the given object to the specified type. |
ConvertToType(Object, Type)
Converte o objeto especificado no tipo especificado.Converts the specified object to the specified type.
public:
System::Object ^ ConvertToType(System::Object ^ obj, Type ^ targetType);
public object ConvertToType (object obj, Type targetType);
member this.ConvertToType : obj * Type -> obj
Public Function ConvertToType (obj As Object, targetType As Type) As Object
Parâmetros
- obj
- Object
O objeto a ser convertido.The object to convert.
- targetType
- Type
O tipo no qual converter o objeto.The type to convert the object to.
Retornos
A cadeia de caracteres JSON serializada.The serialized JSON string.
Exceções
A cadeia de caracteres formatada como JSON excede o valor de MaxJsonLength.The resulting JSON-formatted string exceeds the value of MaxJsonLength.
- ou --or-
obj contém uma referência circular.obj contains a circular reference. Uma referência circular ocorre quando um objeto filho tem uma referência a um objeto pai e o objeto pai tem uma referência ao objeto filho.A circular reference occurs when a child object has a reference to a parent object, and the parent object has a reference to the child object.
O limite de recursão definido pelo RecursionLimit foi excedido.The recursion limit defined by RecursionLimit was exceeded.
Comentários
Quando a JavaScriptSerializer instância está serializando um tipo para o qual um conversor personalizado está registrado, o serializador chama o Serialize método para obter o dicionário de pares de nome/valor que será convertido em uma cadeia de caracteres formatada em JSON.When the JavaScriptSerializer instance is serializing a type for which a custom converter is registered, the serializer calls the Serialize method to obtain the dictionary of name/value pairs that will be converted to a JSON-formatted string.
O Serialize método também pode gerar exceções se o gráfico do objeto for muito complexo ou se instâncias registradas do JavaScriptConverter tiverem causado a recursão do conversor.The Serialize method can also throw exceptions if the object graph is too complex, or if registered instances of JavaScriptConverter have caused converter recursion.
Aplica-se a
ConvertToType<T>(Object)
Converte o objeto fornecido no tipo especificado.Converts the given object to the specified type.
public:
generic <typename T>
T ConvertToType(System::Object ^ obj);
public T ConvertToType<T> (object obj);
member this.ConvertToType : obj -> 'T
Public Function ConvertToType(Of T) (obj As Object) As T
Parâmetros de tipo
- T
O tipo para o qual o obj será convertido.The type to which obj will be converted.
Parâmetros
- obj
- Object
O objeto a ser convertido.The object to convert.
Retornos
- T
O objeto que foi convertido para o tipo de destino.The object that has been converted to the target type.
Exceções
O obj (ou um membro aninhado de obj) contém uma propriedade "__type" que indica um tipo personalizado, mas o resolvedor de tipo associado ao serializador não consegue encontrar um tipo gerenciado correspondente.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.
- ou --or-
O obj (ou um membro aninhado de obj) contém uma propriedade "__type" que indica um tipo personalizado, mas o resultado da desserialização da cadeia de caracteres JSON correspondente não pode ser atribuído ao tipo de destino esperado.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.
- ou --or-
O obj (ou um membro aninhado de obj) contém uma propriedade "__type" que indica Object ou um tipo que não pode ser instanciado (por exemplo, um tipo abstrato ou uma interface).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).
- ou --or-
Foi feita uma tentativa de converter obj em um tipo gerenciado semelhante a uma matriz, que não tem suporte para uso como um destino de desserialização.An attempt was made to convert obj to an array-like managed type, which is not supported for use as a deserialization target.
- ou --or-
Não é possível converter obj em T.It is not possible to convert obj to T.
obj é um tipo de dicionário e um valor de chave que não é uma cadeia de caracteres foi encontrado.obj is a dictionary type and a non-string key value was encountered.
- ou --or-
obj inclui definições de membro que não estão disponíveis no tipo T.obj includes member definitions that are not available on type T.
Exemplos
O exemplo a seguir mostra como usar o ConvertToType método para obter um ListItem objeto de um valor no dicionário que é passado para o conversor.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. Este exemplo de código faz parte de um exemplo maior fornecido para a JavaScriptSerializer classe.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]));
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
Comentários
O ConvertToType método tenta converter a instância do objeto que é representada por obj em uma instância do tipo T .The ConvertToType method tries to convert the object instance that is represented by obj to an instance of type T. Durante essa conversão, não há nenhuma garantia de que a igualdade de referência de objeto é mantida.During this conversion there is no guarantee that object reference equality is maintained. Portanto, você não pode pressupor que obj e T se referir ao mesmo objeto.Therefore, you cannot assume that obj and T refer to the same object.
ConvertToType destina-se a ser usado se você implementar uma classe derivada de JavaScriptConverter .ConvertToType is intended to be used if you implement a class that derives from JavaScriptConverter. O código do conversor deve ser capaz de usar um valor que esteja no dicionário que o serializador passa para ele e, em seguida, converter esse valor em uma instância do tipo T .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. Em vez de implementar novamente o código de conversão personalizado para executar essa tarefa, você pode chamar o ConvertToType método do código do conversor.Instead of re-implementing the custom conversion code to perform this task, you can call the ConvertToType method from the converter code.