如何在JSON.Net中序列化期间更改$ type?

时间:2016-11-18 20:42:55

标签: c# json.net

重复Using a custom type discriminator to tell JSON.net which type of a class hierarchy to deserialize

JsonConverter how to deserialize to generic object

Thx https://stackoverflow.com/users/3744182/dbc

消费者应用程序知道A类,我将服务于继承自A类的B类。在服务器应用程序中定义了B类。

public class A {} // Both Application know it
public class B:A{} // It is defined in Server Application
public A GetAInstanceById(){ // It is written in Server Application, but both application know its method signature, consumer application calls it by simple Web Call
   ..............
   return new B();
}

B响应由JsonConvert.SerializeObject方法序列化,具有此设置。

settings.TypeNameHandling = TypeNameHandling.All;

当消费者应用程序从服务器应用程序获取响应时,它会尝试反序列化对A的响应(因为方法签名)

Json.Net无法找到B类并将实例转换为“对象”并抛出“object Must Implement IConvertible”异常。

所以我想将响应序列化为$ type:“A”。如何更改$ type:“B”到$ type:“A”

0 个答案:

没有答案