HttpClient PostAsJsonAsync 方法无法正常工作(序列化无法正常工作)
HttpClient PostAsJsonAsync method not works correctly(Serialization not works correctly)
我有一个 Web api 控制器并且我使用了 HttpClient PostAsJsonAsync() 方法;我的对象(Employee)继承自基础class(Person),但是在对象发布到Api之后,对象类型发生了变化(正确反序列化);
这是我的 classes:-
发送前对象类型为Employee
Sending后Object类型为Person
请看附件
public class Person
{
public Guid Id { get; set; }
public String Name { get; set; }
}
public class Employee : Person
{
public int Age { get; set; }
}
public class CreateEmployeeRequest
{
public Person Person { get; set; }
}
Before Sending, the Object type is Employee After Sending, the Object type is Person.
那么,序列化工作完美。您的 CreateEmployeeRequest
对象包含一个 Person
对象,而不是雇员。这就是您在另一端看到它的原因。
如果你想反序列化派生,你必须在你的 JSON 中传递 $type
标志来指定它应该反序列化到哪个派生类型,使用 TypeNameHandling
属性 共 JsonSerializerSettings
:
string jsonTypeNameAll = JsonConvert.SerializeObject(employeeRequest, Formatting.Indented, new JsonSerializerSettings
{
TypeNameHandling = TypeNameHandling.All
});
我有一个 Web api 控制器并且我使用了 HttpClient PostAsJsonAsync() 方法;我的对象(Employee)继承自基础class(Person),但是在对象发布到Api之后,对象类型发生了变化(正确反序列化); 这是我的 classes:- 发送前对象类型为Employee Sending后Object类型为Person 请看附件
public class Person
{
public Guid Id { get; set; }
public String Name { get; set; }
}
public class Employee : Person
{
public int Age { get; set; }
}
public class CreateEmployeeRequest
{
public Person Person { get; set; }
}
Before Sending, the Object type is Employee After Sending, the Object type is Person.
那么,序列化工作完美。您的 CreateEmployeeRequest
对象包含一个 Person
对象,而不是雇员。这就是您在另一端看到它的原因。
如果你想反序列化派生,你必须在你的 JSON 中传递 $type
标志来指定它应该反序列化到哪个派生类型,使用 TypeNameHandling
属性 共 JsonSerializerSettings
:
string jsonTypeNameAll = JsonConvert.SerializeObject(employeeRequest, Formatting.Indented, new JsonSerializerSettings
{
TypeNameHandling = TypeNameHandling.All
});