【问题标题】:HttpClient PostAsJsonAsync method not works correctly(Serialization not works correctly)HttpClient PostAsJsonAsync 方法不能正常工作(序列化不能正常工作)
【发布时间】:2015-06-29 21:33:09
【问题描述】:

我有一个 Web api 控制器,我使用了 HttpClient PostAsJsonAsync() 方法;我的对象(Employee)是从基类(Person)继承的,但是在将对象发布到 Api 之后,对象类型发生了变化(未正确序列化); 这是我的课程:- 发送前,Object 类型为 Employee 发送后,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; }
}

【问题讨论】:

    标签: c# json serialization asp.net-web-api async-await


    【解决方案1】:

    发送前Object类型为Employee 发送后Object类型为Person。

    那么,序列化工作完美。您的 CreateEmployeeRequest 对象包含 Person 对象,而不是员工。这就是你在另一端看到它的原因。

    如果您希望能够反序列化派生,则必须使用 JsonSerializerSettingsTypeNameHandling 属性在 JSON 中传递 $type 标志以指定应将其反序列化为哪个派生类型:

    string jsonTypeNameAll =   JsonConvert.SerializeObject(employeeRequest,  Formatting.Indented, new JsonSerializerSettings
    {
        TypeNameHandling = TypeNameHandling.All
    });
    

    【讨论】:

    • 感谢您的帮助;但我想知道如何使用您的解决方案;请提供示例
    • 我将 jsonTypeNameAll 传递给 client.PostAsJsonAsync() 但它不起作用
    • 我在等你的帮助
    • @Ahmed 你是怎么做到的? PostAsJsonAsync 不接受任何序列化设置。
    • var data = JsonConvert.SerializeObject(createEmployeeRequest, Formatting.Indented, new JsonSerializerSettings { TypeNameHandling = TypeNameHandling.All }); var response = await client.PostAsJsonAsync("api/OrganizationService", data);
    猜你喜欢
    • 2016-08-01
    • 2012-11-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多