本文介绍了JSON.NET摘要/派生类反序列化具有的WebAPI 2的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我实现Web API 2服务使用JSON.NET进行序列化。

I'm implementing a Web API 2 service that uses JSON.NET for serialization.

当我试图把(deseralize)更新JSON数据,该抽象类并非present这意味着它不知道如何处理它,所以它什么也没做。我也试图使该类不是抽象的,并从它只是继承,然后deseralized基类,而不是derrived类缺少derrived类的属性每个人都戴上。

When I try to PUT ( deseralize ) updated json data, the abstract class is not present meaning it didn't know what to do with it so it did nothing. I also tried making the class NOT abstract and just inheriting from it and then each PUT deseralized to the base class rather than the derrived class missing the properties of the derrived class.

例如:

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;}
}

我的网络API配置做类型名处理:

with my web api configured to do typename handling:

public static void Register(HttpConfiguration config)
{
     config.Formatters.JsonFormatter.SerializerSettings.TypeNameHandling =
            TypeNameHandling.Objects;
}

后来我把JSON这样的:

then I PUT the JSON like:

{
     people: [{
          name: "Larry",
          id: "123",
          badge: "12345",
          $type: "API.Models.Employee, API"
     }]
}

到Web API方法:

to the web api method:

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

但输出检查时总是:

People == { People: [] }

如果非摘要:

or if non-abstract:

People == { People: [{ Name: "Larry", Id: "123" }] }

缺少inherrited财产。任何人都遇到了这个问题,并想出了什么?

missing the inherrited property. Anyone ran into this problem and come up with anything?

推荐答案

$类型函数必须在对象的第一个属性。

The $type function has to be the first attribute in the object.

在上面的例子中我所做的:

In the above example I did:

 {
   people: [{
      name: "Larry",
      id: "123",
      badge: "12345",
      $type: "API.Models.Employee, API"
   }]
 }

移动 $类型顶端等之后:

 {
   people: [{
      $type: "API.Models.Employee, API",
      name: "Larry",
      id: "123",
      badge: "12345"
   }]
 }

串行器能够对象deseralize到正确的演员。爱是爱了!

the serializer was able to deseralize the object to the correct cast. Gotta love that!

这篇关于JSON.NET摘要/派生类反序列化具有的WebAPI 2的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-05 18:13