使用WebAPI进行JSON.NET抽象/派生类反序列化2

amc*_*dnl 19 .net c# json.net asp.net-web-api

我正在实现一个使用JSON.NET进行序列化的Web API 2服务.

当我尝试PUT(deseralize)更新的json数据时,抽象类不存在意味着它不知道如何处理它所以它什么也没做.我也尝试使类不是抽象的,只是从它继承,然后每个PUT被解除分类到基类而不是缺少类的缺少类的属性.

例:

public class People
{
      // other attributes removed for demonstration simplicity

      public List<Person> People { get;set; }
}

public abstract class Person
{
      public string Id {get;set;}
      public string Name {get;set;}
}

public class Employee : Person 
{
      public string Badge {get;set;}
}

public class Customer : Person
{
     public string VendorCategory {get;set;}
}
Run Code Online (Sandbox Code Playgroud)

我的web api配置为进行typename处理:

public static void Register(HttpConfiguration config)
{
     config.Formatters.JsonFormatter.SerializerSettings.TypeNameHandling = 
            TypeNameHandling.Objects;
}
Run Code Online (Sandbox Code Playgroud)

然后我把JSON像:

{
     people: [{
          name: "Larry",
          id: "123",
          badge: "12345",
          $type: "API.Models.Employee, API"
     }]
}
Run Code Online (Sandbox Code Playgroud)

到web api方法:

public HttpResponseMessage Put(string id, [FromBody]People value)
{
      people.Update(value); // MongoDB Repository method ( not important here )
      return Request.CreateResponse(HttpStatusCode.OK);
}
Run Code Online (Sandbox Code Playgroud)

但检查时的输出value总是:

People == { People: [] }
Run Code Online (Sandbox Code Playgroud)

或者如果不是抽象的:

People == { People: [{ Name: "Larry", Id: "123" }] }
Run Code Online (Sandbox Code Playgroud)

缺少继承的属性.任何人遇到这个问题并想出任何东西?

amc*_*dnl 24

$type函数必须是对象中的第一个属性.

在上面的例子中我做了:

 {
   people: [{
      name: "Larry",
      id: "123",
      badge: "12345",
      $type: "API.Models.Employee, API"
   }]
 }
Run Code Online (Sandbox Code Playgroud)

移动$type到顶部后像:

 {
   people: [{
      $type: "API.Models.Employee, API",
      name: "Larry",
      id: "123",
      badge: "12345"
   }]
 }
Run Code Online (Sandbox Code Playgroud)

序列化程序能够将对象deseralize到正确的强制转换.一定要喜欢!

  • 或者,您可以在序列化时使用`config.Formatters.JsonFormatter.SerializerSettings.TypeNameHandling = TypeNameHandling.Auto;` (5认同)