JsonConverter how to deserialize to generic object

前端 未结 1 1397
谎友^
谎友^ 2021-01-16 21:16

I\'m sending this structure through webapi:

[DataContract]
public class PacketData
{
    public enum Opcodes
    {
        Hello = 0x00,
        Close = 0x01         


        
1条回答
  •  北恋
    北恋 (楼主)
    2021-01-16 22:10

    To answer your updated question, "how do I remap assembly names when exchanging JSON data containing $type information between different .Net assemblies using Json.NET", you have a few options:

    1. The simplest would be to extract the types in question into a shared DLL and reference that DLL from both assemblies. This solves the problem and also reduces code duplication.

    2. If you cannot do this, you will need to write your own SerializationBinder, probably inheriting from Json.NET's DefaultSerializationBinder, as is described in the documentation: Custom SerializationBinder. If your classes are not generic, can simply remap the assemblyName:

      public class SimpleAssemblyMappingSerializationBinder : DefaultSerializationBinder
      {
          readonly string oldAssemblyName;
          readonly string newAssemblyName;
      
          public SimpleAssemblyMappingSerializationBinder(string oldAssemblyName, string newAssemblyName)
          {
              this.oldAssemblyName = oldAssemblyName;
              this.newAssemblyName = newAssemblyName;
          }
      
          public override Type BindToType(string assemblyName, string typeName)
          {
              if (assemblyName == oldAssemblyName)
                  assemblyName = newAssemblyName;
              return base.BindToType(assemblyName, typeName);
          }
      }
      

      For a similar binder, see Handling namespace changes with TypeNameHandling.All.

      But if your classes are generic (for instance, if Data is sometimes a List), you will need to parse the generic parameters inside the type name. For an idea of how to do this see How to create a SerializationBinder for the Binary Formatter that handles the moving of types from one assembly and namespace to another. That question is about BinaryFormatter but the answer applies to Json.NET also.

    3. To omit the assembly name and namespace entirely, you could use the binder from Json serialization for Object Data Type for both serialization and deserialization.

    4. Finally, you could consider switching to DataContractJsonSerializer which exchanges type information indirectly by using contract names rather than raw .Net type names. While the data contract serializer is generally less flexible than Json.NET, its contract-based exchange of type information may be more suitable in this case. See for instance How to deserialize JSON with unnamed collection of types using DataContractSerializer.

    0 讨论(0)
提交回复
热议问题